3.2Doubly Linked List
Inserting at a position
Inserting at a position puts a new node between two nodes, at a given index. In a singly linked list two links change; in a doubly linked list four do. In this lesson you will see the order in which those four links are set and what happens at both ends of the list.
- How the nodes that will sit before and after the new node are found
- The four links that change and why the order of the assignments matters
- How position 0, position equal to the length, and an invalid position are handled
1Idea
Positions start at 0. Inserting at position 2 means the new node takes slot number 2, that is, it goes after two nodes. The code carries two pointers: before points to the node that will sit to the left of the new node, after to the one on its right. They start as NULL and head and move forward together pos times.
Then four links are set. The new node's own links come first: its prev field points to before and its next field to after. These two assignments do not touch the list, so even if something goes wrong the list stays intact. Then the neighbours are pointed at the new node: before->next and after->prev.
The edge cases come out of the same code. With position 0 the loop never runs, before stays NULL and head is moved to the new node: that is inserting at the head. With position equal to the length, after is NULL and the new node is inserted at the end. With a larger or negative position the list stays unchanged.
2Step by step
The drawing inserts 5 at position 2 of a list holding 12, 7 and 3. Blue arrows are prev links; there is room between 7 and 3 for the new node. At each step the matching line of code lights up.
- Start. head points to 12. We will insert 5 at position 2, between 7 and 3.
beforestarts as NULL andafteras head. The loop will runpostimes, that is, twice.- First round:
beforemoves to 12 andafterto 7. - Second round:
beforemoves to 7 andafterto 3. The loop ends. The new node will go between these two. - The new node is created and its own two links are set first: prev points to 7 and next to 3. The list has not changed yet.
beforeis not NULL, so the next field of 7 is pointed at the new node. Going forward from 7 now reaches 5.afteris not NULL, so the prev field of 3 is pointed at the new node. Going back from 3 now reaches 5.- Result: 12 ⇄ 7 ⇄ 5 ⇄ 3. Four links changed; no other link was touched.
struct Node { int data; struct Node* prev; struct Node* next;}; void insertAt(struct Node** head, int pos, int value) { if (pos < 0) return; struct Node* before = NULL; // will sit left of the new node struct Node* after = *head; // will sit right of the new node for (int i = 0; i < pos; i++) { if (after == NULL) return; // position past the end before = after; after = after->next; } struct Node* node = malloc(sizeof(struct Node)); node->data = value; node->prev = before; node->next = after; if (before != NULL) before->next = node; else *head = node; // position 0: insert at head if (after != NULL) after->prev = node;}class Node { int data; Node prev, next; Node(int data) { this.data = data; }} Node insertAt(Node head, int pos, int value) { if (pos < 0) return head; Node before = null; // will sit left of the new node Node after = head; // will sit right of the new node for (int i = 0; i < pos; i++) { if (after == null) return head; // position past the end before = after; after = after.next; } Node node = new Node(value); node.prev = before; node.next = after; if (before != null) before.next = node; else head = node; // position 0: insert at head if (after != null) after.prev = node; return head;}class Node: def __init__(self, data): self.data = data self.prev = None self.next = None def insert_at(head, pos, value): if pos < 0: return head before = None # will sit left of the new node after = head # will sit right of the new node for _ in range(pos): if after is None: return head # position past the end before = after after = after.next node = Node(value) node.prev = before node.next = after if before is not None: before.next = node else: head = node # position 0: insert at head if after is not None: after.prev = node return headThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Walking to the position takes up to n steps in the worst case. Setting the four links takes constant time.
No space is needed apart from the new node and two pointers.
The slow part is finding the position, not linking. If you already hold the node next to which the new one goes, the insertion is O(1).
4Common mistake
The most common mistake is changing the neighbours' links in the wrong order. For example, holding only before and writing:
before->next = node;node->next = before->next; // now the new node itselfnode->next->prev = node;The first line changes before->next, so the second line reads the new node's own address instead of the address of 3. The new node points to itself and everything after it is lost. The rule: set the new node's links from the old values first, change the neighbours last. Do not forget the NULL check either: when inserting at the end after is NULL and writing after->prev crashes the program.
5Try it
What happens if insertAt is called with position 3 on the list 12 ⇄ 7 ⇄ 3?
The answer is B. The position equals the length of the list (3). When the loop ends, before points to the last node (3) and after is NULL. The new node's next field becomes NULL and the after->prev line is skipped: this is inserting at the end. Positions 4 and above are invalid.
Show the answer
The answer is B. The position equals the length of the list (3). When the loop ends, before points to the last node (3) and after is NULL. The new node's next field becomes NULL and the after->prev line is skipped: this is inserting at the end. Positions 4 and above are invalid.
How many pointer fields change when inserting in the middle? (Not at position 0 or at the end)
Lessons you mark show up in the curriculum. This is kept on this device only.