Inserting and deleting in a linked list
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↓1node = Node(5)2node.next = p.next3p.next = node
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))
[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.
A list has n items. How many items move for a.insert(0, x), which puts x at the front?
Put these three lines in order to insert 5 after 3, so the program prints [3, 5, 7, 9].
p.next = nodenode = Node(5)node.next = p.next
[3, 5, 7, 9]
node.next = p.next points 5 at 7; then fix the front: p.next = node. Swap the last two and 7 and 9 are lost, and 5 ends up pointing at itself.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.
[1, 2, 3, 4] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
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))
What if the order is wrong
Swap the two lines, so p.next = node comes first:
p↓1node = Node(5)2p.next = node3node.next = p.next
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)
p.next = node, p.next is the new node, so node.next = p.next makes 5 point at itself. From 3 the walk reaches 5 and then goes round and round on 5, never reaching None: without the 6-step limit, while cur would loop forever. The 7 and 9 were lost long before.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↓1p.next = p.next.nextPython 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:
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)
[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.
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))
p.next = p.next.next. Nothing refers to 7 any more, so Python reclaims it on its own.What does del node do?
del removes a name and nothing more. If a node in the list still has a next pointing at it, or another name refers to it, it stays. Taking a node out of a list is done by changing the next of the node before it.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:
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)))
[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↓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
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.
| Operation | linked list | list |
|---|---|---|
| Insert after a node p you already hold | O(1): 2 references change | no equivalent: only by index |
| Delete the node after p | O(1): 1 reference changes | the same |
| Insert or delete at position i | O(i): walk to item i − 1 first | O(n − i): move what follows |
| Holding only the node to delete | the node before it cannot be found: O(n), or copy the next value | — |
| Insert or delete at the front | O(1) | O(n) |
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)
head inside the function is just a local name. head = node points that local name at the new node, while the head outside still points at 3. To make the change visible, return the new head, head = push_front(head, 1), or write a list class and change self.head.With a dummy node, dummy = Node(0, head), how do you tell the list is empty?
dummy itself is never None; the list is empty when there is no node after it. The dummy’s value is not used, so the 0 in it tells you nothing.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.
[0, 1, 3] [0, 1, 2, 3] [0, 1, 2, 3, 4]
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))
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:
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")
7 done
del nameremoves 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.
You already hold node p and insert after it. Compare that with inserting at position i. What are the two time complexities?
a = Node(7), b = a, then del a. What now?
del a only removes the name a. b still refers to the same object, so its count is not 0 and it is not reclaimed. It goes only once no name and no reference points at it.Summary
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