Skip to Content
🧮 CTDL & Giải thuật🔗 Danh sách liên kết

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

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

def traverse(head): current = head while current: print(current.data, end=" -> ") current = current.next print("null")

Đảo ngược Linked List

def reverse(head): prev = None current = head while current: next_node = current.next current.next = prev prev = current current = next_node return prev # New head

Tìm điểm giữa (Floyd’s Algorithm)

def find_middle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow

Phát hiện vòng lặp

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 False

So sánh với Array

Thao tácArrayLinked List
Truy cập theo indexO(1) ✅O(n) ❌
Thêm/xóa đầuO(n) ❌O(1) ✅
Thêm/xóa cuốiO(1) ✅O(n) hoặc O(1)*
Bộ nhớLiên tụcPhân tán

Tiếp theo: Ngăn xếp (Stack)

Last updated on