ENع
→Linked lists
الدرس 06 · Linear structures in depth

Linked lists: singly, doubly and circular

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة8 خطوات5 أسئلةBeginner
عن هذا الدرس

A linked list stores each item in its own node, and each node holds a link to the next one. Build the list 3 → 7 → 9 in Python, walk it, add a node at the front, insert one in the middle and remove one, and watch that no node ever moves: only the links swing. Then give every node a second link for a doubly linked list, and point the end back at the start for a circular one. The Software lessons "Arrays and lists" and "Stacks and queues" cover the array side of the comparison.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 6 · تفاعلي
01 / 08

A node: value plus link

A linked list keeps each item in its own small object called a node. A node holds two things: the value, here 3, and next, a reference (an arrow) to the node after it. Nodes can sit anywhere in memory.

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

Node(3) makes one node:
  value = 3
  next  = None until we link it
a reference is how Python names an object: an arrow, not a copy
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A node: value plus link

    A linked list keeps each item in its own small object called a node. A node holds two things: the value, here 3, and next, a reference (an arrow) to the node after it. Nodes can sit anywhere in memory.

    class Node:
        def __init__(self, value, next=None):
            self.value = value
            self.next = next
    
    Node(3) makes one node:
      value = 3
      next  = None until we link it
    a reference is how Python names an object: an arrow, not a copy
  2. Follow the links from head

    head is a variable that refers to the first node. Each next points to the following node: 3, then 7, then 9. The last next is None, which marks the end. Python built this list with Node(3, Node(7, Node(9))).

    head = Node(3, Node(7, Node(9)))
    
    head     -> node 3
    node 3.next -> node 7
    node 7.next -> node 9
    node 9.next -> None   (the end)
    
    values(head) == [3, 7, 9]
  3. Walking to a value

    There is no index to jump to. To find 7, node starts at head and follows next, one link at a time, until it holds 7. Reaching position k takes k hops: O(n) in the worst case, where a Python list index takes O(1).

    1  node = head              node -> 3
    2  while node.value != 7:    3 != 7, go on
    3      node = node.next     node -> 7 (1 hop)
    2  while node.value != 7:    7 == 7, stop
    
    position k needs k hops; the last of n items needs n - 1
    get by position: O(n) worst case (array: O(1))
  4. Add at the front in O(1)

    Node(1, head) makes a new node whose next is the old first node, 3. Then head moves to the new node. That is two link writes however long the list is: O(1). A Python list's insert(0, x) moves every item over: O(n).

    4  head = Node(1, head)
    
      new node 1, its next -> node 3 (the old head)
      head -> node 1
    
    values(head) == [1, 3, 7, 9]
    two writes for any length: O(1)
    list.insert(0, x) moves n items: O(n)
  5. Insert in the middle

    To put 8 after 7, the new node first points at 7's old next, 9. Then 7's next moves to the new node. Nothing shifts in memory; two links change. Do it in this order, or 9 is lost.

    5  new = Node(8, node.next)   new.next -> 9
    6  node.next = new            7.next -> 8
    
    values(head) == [1, 3, 7, 8, 9]
    given node, inserting after it is O(1);
    finding node first was the O(n) walk
    
    wrong order: node.next = new first
    and nothing refers to 9 any more
  6. Unlink a node

    To remove 3, link around it: old holds node 3, then 1's next jumps over it to old.next, 7. No link in the list reaches 3 now, so once old is dropped Python can free it. No shifting, just one write.

    7  old = head.next      old -> node 3
    8  head.next = old.next  node 1.next -> node 7
    
    values(head) == [1, 7, 8, 9]
    removing the node after one you hold: O(1)
    unreachable objects may be garbage-collected
  7. Doubly linked: both ways

    A doubly linked list gives each node a second link, prev, to the node before it. You can now walk backwards, and unlink a node you hold in O(1): node.prev.next = node.next, then node.next.prev = node.prev. The price: one more reference per node.

    each node: prev | value | next
      1.prev = None   9.next = None
    
    walk back from 9: [9, 8, 7, 1]
    
    def unlink(node):
        node.prev.next = node.next
        node.next.prev = node.prev
    unlink(node 8) -> [1, 7, 9], O(1)
  8. Circular: the end links back

    Back to single links. In a circular list the last node's next points to the first instead of None. A walk never runs off the end, so a loop must stop when it is back at the start. It suits anything that takes turns.

    tail.next = head        node 9.next -> node 1
    
    node = head
    while True:
        out.append(node.value)
        node = node.next
        if node is head:
            break
    
    out == [1, 7, 8, 9]   (no None to stop at)

اختبار يتاح بعد الخطوة الأخيرة.