Danh sách liên kết (Linked List)
Linked List là gì?
Linked List là cấu trúc dữ liệu gồm các node kết nối với nhau bằng con trỏ (pointer). Mỗi node chứa dữ liệu và địa chỉ của node tiếp theo.
┌──────┬──────┐ ┌──────┬──────┐ ┌──────┬──────┐
│ 10 │ next │───▶│ 20 │ next │───▶│ 30 │ null │
└──────┴──────┘ └──────┴──────┘ └──────┴──────┘
Head Tail💡
Linked List như một đoàn tàu - mỗi toa (node) chứa hàng hóa (data) và móc nối với toa sau!
Cài đặt Node
Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Tạo linked list: 1 -> 2 -> 3
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)Duyệt Linked List
Python
def traverse(head):
current = head
while current:
print(current.data, end=" -> ")
current = current.next
print("null")Đảo ngược Linked List
Python
def reverse(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev # New headTìm điểm giữa (Floyd’s Algorithm)
Python
def find_middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slowPhát hiện vòng lặp
Python
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return FalseSo sánh với Array
| Thao tác | Array | Linked List |
|---|---|---|
| Truy cập theo index | O(1) ✅ | O(n) ❌ |
| Thêm/xóa đầu | O(n) ❌ | O(1) ✅ |
| Thêm/xóa cuối | O(1) ✅ | O(n) hoặc O(1)* |
| Bộ nhớ | Liên tục | Phân tán |
Tiếp theo: Ngăn xếp (Stack)
Last updated on