Insert and delete
After this: Change two pointers in the right order, and say what the wrong order loses.
On this page · 8 sections · 4 checks
You have seen that inserting a node takes two pointer writes. This lesson looks closely at those two writes, and then at deleting.
Here is the question. The list is 3 → 7 → 9, and 5 has to go after 3. Two pointers must change: the new node's, and the one in 3. Does it matter which you write first?
It matters a great deal. One order works. The other order loses part of the list.
Insert: the order that works
- Create a new node holding 5. It points at nothing yet.
- Point the new node at 7, the node that 3 points at now. Both 3 and the new node point at 7 for a moment. The list has not changed, so nothing can be lost.
- Point 3 at the new node.
The list is now 3 → 5 → 7 → 9. Nodes 7 and 9 were never touched.
Insert: the order that fails
Now try the same two writes the other way round.
- Create a new node holding 5.
- Point 3 at the new node. The
nextin 3 was the only pointer that led to 7, and you have overwritten it. Nothing points at 7 now. - Try to point the new node at "whatever comes after 3". That is now the new node itself.
Nodes 7 and 9 are still in memory, but your program has no way to get to them. A node that cannot be reached by following pointers from the head is called .
The treasure hunt shows the same problem. If you rub out "under the doormat" on the first clue before you copy it onto the new clue, nobody knows where the rest of the hunt is hidden.
Here is that mistake in code.
head = build([3, 7, 9])new = Node(5)head.next = new # 3 now points at 5. Nothing points at 7 any more.new.next = head.next # meant to be 7, but head.next is already the new nodeprint(new.next is new) # the new node points at itself; 7 -> 9 is unreachableTrue
Node head = build(3, 7, 9);Node fresh = new Node(5);head.next = fresh; // 3 now points at 5. Nothing points at 7 any more.fresh.next = head.next; // meant to be 7, but head.next is already the new nodeSystem.out.println(fresh.next == fresh); // the new node points at itself; 7 -> 9 is unreachabletrue
The last line prints whether the new node's next is the new node itself, and it is. If you called show on this list, it would never finish and would print nothing, because the walk would stay on the new node forever. The visualizer draws the same mistake a little differently, so that you can see what was lost. It shows the new node pointing nowhere, and it shows 7 and 9 below the chain as unreachable.
Delete: point past the node
Deleting takes one pointer write. To delete 7 from 3 → 5 → 7 → 9:
- Walk to 5, the node before 7.
- Point 5 at 9, the node after 7.
The list is now 3 → 5 → 9. No node is moved, and no pointer in the list leads to 7 any more.
Notice that the walk has to stop on the node before the target. The pointer you need to change is in that node, and a node cannot look backwards. If you stopped on 7, you could not reach 5.
There is one special case. Nothing in the list points at the first node, so there is no node before it. To delete the first node, the list starts one node later: head moves to the second node.
The code
def insert_after(node, value): new = Node(value) new.next = node.next # 1. the new node points at what came next node.next = new # 2. only then does node point at the new node
def delete(head, value): if head.value == value: # deleting the head: the list starts one node later return head.next prev = head while prev.next is not None and prev.next.value != value: prev = prev.next # stop on the node *before* the target if prev.next is not None: prev.next = prev.next.next # point past it; nothing shifts return headstatic void insertAfter(Node node, int value) { Node fresh = new Node(value); fresh.next = node.next; // 1. the new node points at what came next node.next = fresh; // 2. only then does node point at the new node}
static Node delete(Node head, int value) { if (head.value == value) return head.next; // deleting the head: the list starts one node later Node prev = head; while (prev.next != null && prev.next.value != value) { prev = prev.next; // stop on the node *before* the target } if (prev.next != null) prev.next = prev.next.next; // point past it; nothing shifts return head;}Here is how to read it.
- The highlighted lines are the two pointer writes of the insert, in the order that works.
deletehandles the special case first. If the first node holds the value, it returnshead.next, the new first node.- Otherwise
prevstarts at the head and walks along.prevmeans the previous node. The loop checks the node afterprev, so it stops on the node before the target, or on the last node if the value is not in the list. - If the target was found,
prev.next = prev.next.nextpointsprevpast it. If it was not found, nothing changes. deletereturns the head, so the caller writeshead = delete(head, 7).
head = build([3, 7, 9])insert_after(find(head, 3), 5)print(show(head))head = delete(head, 7)print(show(head))head = delete(head, 3)print(show(head))3 -> 5 -> 7 -> 9 3 -> 5 -> 9 5 -> 9
Node head = build(3, 7, 9);insertAfter(find(head, 3), 5);System.out.println(show(head));head = delete(head, 7);System.out.println(show(head));head = delete(head, 3);System.out.println(show(head));3 -> 5 -> 7 -> 9 3 -> 5 -> 9 5 -> 9
What insert and delete cost
If you hold the node to insert after, the insert is O(1). The delete above takes a value, so it has to walk to the node before the target. That walk is O(n), and the pointer write after it is O(1).
If you hold only the node you want to delete, you still need a walk, because that node cannot tell you which node is before it. A later lesson, on doubly linked lists, removes that walk.
Watch it happen
Here is the right order, then a delete that puts the list back, then the wrong order on the same list.
- Insert 5 after 3Insert 5 after 3. First the new node is pointed at 7. Only then is 3 pointed at the new node.
- Delete 5
- Insert 5 after 3 (wrong order)
Run an operation to begin.
After the wrong order, the unreachable nodes are drawn below the chain.
Check yourself
The list is 3 → 7 → 9. To insert 5 after 3, you point 3 at the new node first, before the new node points at anything. Which nodes can still be reached from head?
The list is 3 → 5 → 7 → 9. To delete 7, which pointer is changed, and to what?
You delete a value from a list of n nodes that has only next pointers. Which cost is right?
What does this print?
head = build([3, 7, 9])insert_after(find(head, 3), 5)print(show(head))head = delete(head, 7)print(show(head))head = delete(head, 3)print(show(head))Node head = build(3, 7, 9);insertAfter(find(head, 3), 5);System.out.println(show(head));head = delete(head, 7);System.out.println(show(head));head = delete(head, 3);System.out.println(show(head));Connect
- Insert after a node: point the new node at what comes next first, then point the node before it at the new node.
- Say what the other order loses: everything after the place you inserted.
- Delete by stopping on the node before the target and pointing it past the target.