Kodewick
Start learning →
Inserting and deleting in a linked list10 / 52

Inserting and deleting in a linked list

Lesson 10 of 52 · Part 2 · Names, lists and linked lists · about 16 minutes

Inserting and deleting in a linked list only change references: holding the node p before the spot, an insert sets node.next = p.next before p.next = node, a delete changes one reference, and a dummy head removes the special case of the first node.

Insert a number in the middle of a list and everything after it moves; in a linked list, as long as you hold the node p before the spot, inserting a new node changes 2 references and deleting the one after p changes 1, whether the list has 10 nodes or 100,000. But get those two or three lines in the wrong order and the whole second half of the list is lost, with no error. The first node has no "node before it", so every function needs an extra if for it; at the end of this lesson a dummy node gets rid of that if.

Inserting after p: link the back first, then the front

To insert 5 after p: first make the new node point at p's old next node, then make p point at the new node.

p↓
3a
5d
7b
9c
None
1node = Node(5)2node.next = p.next3p.next = node

Inserting 5 after 3: first the new node points at 7 (the back), then 3 points at the new node (the front)
main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def to_list(head):7    out = []8    while head:9        out.append(head.val)10        head = head.next11    return out12 13def insert_after(p, val):14    node = Node(val)15    node.next = p.next16    p.next = node17 18head = Node(3, Node(7, Node(9)))19insert_after(head, 5)20print(to_list(head))21insert_after(head.next.next.next, 10)     # after the last node, 922print(to_list(head))
Output
[3, 5, 7, 9]
[3, 5, 7, 9, 10]

Inserting after the last node is the same code: p.next is None, so the new node's next is None.

Choose one

A list has n items. How many items move for a.insert(0, x), which puts x at the front?

Put in orderDrag, or use the arrows

Put these three lines in order to insert 5 after 3, so the program prints [3, 5, 7, 9].

  1. p.next = node
  2. node = Node(5)
  3. node.next = p.next
Should print
[3, 5, 7, 9]
Exercise 1

Insert after target

Finish insert_after_value(head, target, x): find the first node whose value is target and insert x after it; if there is none, do nothing.

It should print
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
exercise1.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def to_list(head):7    out = []8    while head:9        out.append(head.val)10        head = head.next11    return out12 13def insert_after_value(head, target, x):14    # first find the node cur whose value is target; then link the back first, then the front15    pass16 17head = Node(1, Node(2, Node(4)))18insert_after_value(head, 2, 3)19print(to_list(head))20insert_after_value(head, 4, 5)21print(to_list(head))22insert_after_value(head, 9, 0)23print(to_list(head))
Output
Press Run or Ctrl+Enter

What if the order is wrong

Swap the two lines, so p.next = node comes first:

p↓
3a
5d
7b
9c
None
1node = Node(5)2p.next = node3node.next = p.next

The front first: as soon as p.next = node runs, nothing refers to 7 and 9; then node.next = p.next points the new node at itself
Guess the outputA wrong guess is fine

The order is wrong. Walking at most 6 steps, what does it print?

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7p = head8node = Node(5)9p.next = node10node.next = p.next11 12out = []13cur = head14for _ in range(6):15    if cur is None:16        break17    out.append(cur.val)18    cur = cur.next19print(out)

The rule: link the back first, then the front. Changing the front first overwrites the only reference to the second half.

Deleting: let the previous node skip it

Deleting the node after p is one line: p.next = p.next.next.

p↓
3a
7b
9c
None
1p.next = p.next.next

Deleting the 7 after 3: 3 points straight at 9; nothing refers to 7 any more, so Python reclaims it

Python has no free. CPython keeps a count for every object of "how many references point at it", and reclaims it the moment the count reaches 0. The other way round, as long as some other name points at it, it is not reclaimed:

main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def to_list(head):7    out = []8    while head:9        out.append(head.val)10        head = head.next11    return out12 13head = Node(3, Node(7, Node(9)))14p = head15kept = p.next            # another name still points at 716p.next = p.next.next17print(to_list(head))18print(kept.val, kept.next.val)
Output
[3, 9]
7 9

7 is no longer in the list, but kept still points at it, so it is still there, and its next still points at 9. del kept only removes the name kept; the object is reclaimed when the names are gone and its count reaches 0.

Fill inTap one to fill a blank; tap a blank to take it back

Pick what goes in the blank to delete the 7 after 3.

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def to_list(head):7    out = []8    while head:9        out.append(head.val)10        head = head.next11    return out12 13head = Node(3, Node(7, Node(9)))14p = head15p.next = 16print(to_list(head))
Choose one

What does del node do?

Trouble at the front, and the dummy node

Delete every node whose value is x. The first node has no "node before it", and deleting it means changing head itself, so without a dummy node it takes two pieces of code:

main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def to_list(head):7    out = []8    while head:9        out.append(head.val)10        head = head.next11    return out12 13def remove_all(head, x):14    while head and head.val == x:      # the front ones need their own loop15        head = head.next16    cur = head17    while cur and cur.next:18        if cur.next.val == x:19            cur.next = cur.next.next20        else:21            cur = cur.next22    return head23 24print(to_list(remove_all(Node(6, Node(6, Node(1, Node(6, Node(2))))), 6)))25print(to_list(remove_all(Node(6, Node(6)), 6)))
Output
[1, 2]
[]

A dummy node (also called a sentinel or a head node) is a fake node placed in front, whose value is never used. With it, the real first node has a "node before it" too, every node is handled by the same code, and at the end you return dummy.next.

dummy↓prev↓
0z
6a
1b
6c
2d
None
1dummy = Node(0, head)2prev = dummy3while prev.next:4    if prev.next.val == x:5        prev.next = prev.next.next6    else:7        prev = prev.next8return dummy.next

A dummy node in front: the first 6 has a node before it too, so deleting it is the same code as deleting the middle 6

After a delete, prev stays put: once one node is skipped, the new prev.next has not been looked at yet and may be another 6.

In interviews: "Remove linked list elements", "Merge two sorted lists" and "Remove the nth node from the end" all start with dummy = ListNode(0, head) and end with return dummy.next. Another favourite: "You are given only the node to delete (not head); delete it." A singly linked list cannot find the node before it, so copy the next node's value over and delete the next node: node.val = node.next.val; node.next = node.next.next.

Operationlinked listlist
Insert after a node p you already holdO(1): 2 references changeno equivalent: only by index
Delete the node after pO(1): 1 reference changesthe same
Insert or delete at position iO(i): walk to item i − 1 firstO(n − i): move what follows
Holding only the node to deletethe node before it cannot be found: O(n), or copy the next value—
Insert or delete at the frontO(1)O(n)
Guess the outputA wrong guess is fine

push_front is meant to put 1 at the front, but what does the program print?

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def push_front(head, val):7    node = Node(val, head)8    head = node9 10head = Node(3, Node(7))11push_front(head, 1)12print(head.val)
Choose one

With a dummy node, dummy = Node(0, head), how do you tell the list is empty?

Exercise 2

Insert at position i, with a dummy node

Finish insert_at(head, i, x): make x node number i (counting from 0, so 0 means at the front) and return the new head. Use a dummy node, with no separate if for i = 0.

It should print
[0, 1, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
exercise2.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def to_list(head):7    out = []8    while head:9        out.append(head.val)10        head = head.next11    return out12 13def insert_at(head, i, x):14    dummy = Node(0, head)15    # prev walks i steps from dummy: that is the node before the new one16    return dummy.next17 18head = Node(1, Node(3))19head = insert_at(head, 0, 0)20print(to_list(head))21head = insert_at(head, 2, 2)22print(to_list(head))23head = insert_at(head, 4, 4)24print(to_list(head))
Output
Press Run or Ctrl+Enter

How you write it at work

Python has no ready-made singly linked list, and you rarely need one: list and deque cover almost everything. deque.insert(i, x) and del d[i] exist, but they find the spot by index, O(n), not "hold the node and it is O(1)". When you really need to delete or move something at a known spot in the middle in O(1) (an LRU cache, say), write a doubly linked list plus a dict, or just use OrderedDict: that is the next lesson.

About reclaiming, remember two things:

main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6a = Node(7)7b = a8del a            # removes only the name a9print(b.val)     # the object is still there: b points at it10 11x = Node(1)12y = Node(2, x)13x.next = y       # x and y point at each other: a cycle14del x, y         # neither count is 0; gc's cycle finder reclaims them15print("done")
Output
7
done
  • del name removes a name, not an object; an object is reclaimed only when nothing refers to it.
  • Nodes that point at each other (a cycle, a doubly linked list) cannot be reclaimed by counting references alone; CPython also has gc, which looks for such cycles from time to time. Normally you never need to think about it.
Choose one

You already hold node p and insert after it. Compare that with inserting at position i. What are the two time complexities?

Choose one

a = Node(7), b = a, then del a. What now?

Summary

Take-away

To insert, link the back then the front; to delete, let the previous node skip it

  • Insert after p: node.next = p.next, then p.next = node; the other way round loses the rest
  • Delete the node after p: p.next = p.next.next, O(1)
  • No free: an object nothing refers to is reclaimed; del only removes a name
  • A dummy node gives the first node a node before it: no special case, return dummy.next
1node.next = p.next        # link the back first2p.next = node             # then the front3p.next = p.next.next      # delete4dummy = Node(0, head)     # ...  return dummy.next