Python 3D Academyবাংলা

Inserting and deleting by changing links

🌍 In real life. A train at Kamalapur station needs one more coach in the middle. The workers don't move any passengers: they uncouple coach 2 from coach 3, hook the new coach to coach 3, then hook coach 2 to the new coach. Two couplings change, and every other coach stays exactly where it is. Taking a coach out is even simpler: hook the coach in front of it straight to the coach behind it.

Compare the cinema row in Chapter 34, where making room for one person meant everyone after them shifted along a seat.

The idea in one sentence: to insert or delete in a linked list, walk to the node just before the spot and change one or two next links; nothing else moves.

Its words:

  • the node before: the node whose next link must change; you can't walk backwards in a singly linked list
  • dummy head: an extra node in front of the real head, so even the first node has a node before it
  • unlink: skip a node with p.next = p.next.next

How it works, step by step:

  1. insert new after node p: first new.next = p.next (hold on to the rest), then p.next = new
  2. delete the node after p: p.next = p.next.next (it is skipped, and Python frees it once nothing points to it)
  3. at the head there is no node before: insert with head = Node(v, head), delete with head = head.next
  4. to reach position i, walk i − 1 hops to the node before it

Watch two inserts and two deletes. The panel compares the links changed with what an array would have shifted:

Why it is correct. After new.next = p.next and p.next = new, walking from the head reaches p, then new, then exactly the nodes that came after p before: the chain is unbroken with one node added. After p.next = p.next.next, the walk goes from p straight to the node after the deleted one. The order of the two insert steps matters: doing p.next = new first would lose the rest of the list.

What it costs: linked list vs Python list.

  • reach position i: list O(1); linked list O(n) (i hops)
  • insert or delete at the front: list O(n) (everything shifts); linked list O(1)
  • insert or delete after a node you already hold: linked list O(1); list O(n)
  • append at the end: list O(1) on average; linked list O(n), unless you also keep a reference to the last node

So a linked list wins when changes happen at the front, or next to a node you already have, and loses whenever you need positions. Python's deque (Chapter 40) is built from linked blocks for exactly this reason.

A dummy head. Insert and delete need a node before the spot, and the head has none. A common trick is a dummy node in front, dummy = Node(0, head): now every position has a node before it, the head included, and at the end the real head is dummy.next.

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

def to_list(head):          # given: the values, front to back
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out

def insert_after(p, val):
    p.next = Node(val, p.next)     # new.next = p.next, then p.next = new

def delete_value(head, target):
    dummy = Node(0, head)          # a node before the head
    p = dummy
    while p.next and p.next.val != target:
        p = p.next
    if p.next:
        p.next = p.next.next       # skip the node
    return dummy.next

head = Node(3, Node(1, Node(4)))
insert_after(head.next, 7)
print(to_list(head))
head = delete_value(head, 3)       # deleting the head is no special case
print(to_list(head))

Mistakes and edge cases.

  • the wrong order: p.next = new before new.next = p.next makes the new node point at itself, and the rest of the list is lost
  • deleting the head without changing head: the caller still holds the old first node
  • walking i hops instead of i − 1, so you stop on position i and insert one place too late
  • inserting at the end (i equal to the length) and deleting the last node both work with the same code: p.next is None

Quiz

  1. After inserting 7 after 1 in 3 → 1 → 4, walking the list goes round 1 → 7 → 7 → 7 … forever. The two link lines are in the wrong order: which one must run first?

    def insert_after(p, val):
        new = Node(val)
        p.next = new
        new.next = p.next
  2. Which is O(1) for a linked list but O(n) for a Python list?

    • Inserting at the front
    • Reading the item at position i
    • Appending at the end, with no reference to the last node
  3. What does this print?

    class Node:
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    
    head = Node(1, Node(2, Node(3)))
    p = head
    p.next = p.next.next
    head = Node(0, head)
    out = []
    while head:
        out.append(head.val)
        head = head.next
    print(out)
  4. Why put a dummy node in front of the head?

    • So the head also has a node before it, and inserting or deleting there needs no special case
    • To make walking the list faster
    • Because Python lists need it

Coding tasks

  1. Write insert_at(head, i, val): insert a new node with val at position i (0 means in front; the length means at the end) and give back the head of the changed list.

  2. Write delete_value(head, target): remove the first node whose value is target and give back the head of the changed list. If there is none, the list stays the same.