3.2Doubly Linked List
Deleting a node
Deleting a node means taking it out from between its two neighbours and linking the neighbours to each other. In a doubly linked list a node carries the address of the node in front of it. That makes deletion easier than deleting from the middle of a singly linked list: there is no need to search for the previous node.
- Which two assignments link the two neighbours of the deleted node to each other
- How the first node, the last node and a one-node list are handled
- Why removing a node you already hold is O(1)
1Idea
The code first finds the node to delete: it starts at head and moves forward pos times. If the list is empty or the position is outside the list, target becomes NULL and the function returns without changing anything.
Taking the node out of the list is two assignments. The next field of the node in front is pointed at the node behind: target->prev->next = target->next. The prev field of the node behind is pointed at the node in front: target->next->prev = target->prev. Now the two neighbours point to each other and no link leads to the target any more.
At the ends one of the neighbours is missing. When the first node is deleted there is nothing in front of it; instead head is moved to the node behind. When the last node is deleted there is nothing behind it and the second assignment is skipped. In a one-node list both happen and head becomes NULL. In C the memory is finally returned with free; in Java and Python the garbage collector does that.
If you already hold the node to delete (for example, a search returned it), the loop is not needed: the remaining lines take constant time. In a singly linked list holding the node is not enough, because finding the previous node means walking from the start. In a doubly linked list the previous node is in target->prev.
2Step by step
The drawing deletes the node at position 2 (holding 3) from a list holding 12, 7, 3 and 9. Blue arrows are prev links. The node being deleted is drawn one row lower so that the links stay visible. At each step the matching line of code lights up.
- Start. head points to 12. We will delete the node at position 2, which holds 3.
targetstarts at head, that is, at 12.- First round:
targetmoves to 7. - Second round:
targetmoves to 3. The loop ends. The node is not NULL, so it will be deleted. - There is a node in front of 3 (7). The next field of 7 is pointed at the node behind 3, which is 9. The forward path now skips 3.
- There is a node behind 3 (9). The prev field of 9 is pointed at the node in front of 3, which is 7. The backward path skips 3 too.
- No link in the list leads to 3 any more. In C its memory is returned with free.
- Result: 12 ⇄ 7 ⇄ 9. Only two links changed.
struct Node { int data; struct Node* prev; struct Node* next;}; void deleteAt(struct Node** head, int pos) { if (pos < 0) return; struct Node* target = *head; for (int i = 0; i < pos && target != NULL; i++) target = target->next; if (target == NULL) return; // empty list or invalid position if (target->prev != NULL) target->prev->next = target->next; else *head = target->next; // deleting the first node if (target->next != NULL) target->next->prev = target->prev; free(target);}class Node { int data; Node prev, next; Node(int data) { this.data = data; }} Node deleteAt(Node head, int pos) { if (pos < 0) return head; Node target = head; for (int i = 0; i < pos && target != null; i++) target = target.next; if (target == null) return head; // empty list or invalid position if (target.prev != null) target.prev.next = target.next; else head = target.next; // deleting the first node if (target.next != null) target.next.prev = target.prev; return head; // the garbage collector frees the removed node}class Node: def __init__(self, data): self.data = data self.prev = None self.next = None def delete_at(head, pos): if pos < 0: return head target = head for _ in range(pos): if target is None: return head # invalid position target = target.next if target is None: return head # empty list or invalid position if target.prev is not None: target.prev.next = target.next else: head = target.next # deleting the first node if target.next is not None: target.next.prev = target.prev return head # the garbage collector frees the removed nodeThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Finding the node at the position takes up to n steps in the worst case. Taking it out takes constant time.
No space is needed apart from a single pointer.
If you hold the node, deletion is O(1). In a singly linked list deleting the same node requires finding the previous node, which is O(n).
4Common mistake
The most common mistake is writing the two assignments directly, without thinking about the ends:
target->prev->next = target->next;target->next->prev = target->prev;free(target);This is right for a node in the middle. But for the first node target->prev is NULL and the first line writes through NULL; for the last node the second line does the same. The program crashes. Updating head when the first node is deleted is forgotten as well: head keeps pointing to freed memory. Every assignment needs a NULL check in front of it.
5Try it
On a one-node list, which lines run when deleteAt(&head, 0) is called?
If you hold the address of the node to delete, why is deletion O(1) in a doubly linked list?
Lessons you mark show up in the curriculum. This is kept on this device only.