algoritmauzmanı
TREN
3.2Doubly Linked List
Lesson 3.2.4

Inserting at a position

Inserting at a position puts a new 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.

What you will learn
  • 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
7 minTime O(n)Memory O(1)C · Java · Python

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 : 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 and move forward together pos times.

Then four links are set. The new node's own links come first: its field points to before and its 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 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.

NULLNULL12?0x1a407?0x1a903?0x1b205?0x2c10headafterbefore = NULLnode
  1. Start. points to 12. We will insert 5 at position 2, between 7 and 3.
  2. before starts as NULL and after as . The loop will run pos times, that is, twice.
  3. First round: before moves to 12 and after to 7.
  4. Second round: before moves to 7 and after to 3. The loop ends. The new node will go between these two.
  5. The new node is created and its own two links are set first: points to 7 and to 3. The list has not changed yet.
  6. before is not NULL, so the field of 7 is pointed at the new node. Going forward from 7 now reaches 5.
  7. after is not NULL, so the field of 3 is pointed at the new node. Going back from 3 now reaches 5.
  8. 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 head

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

Walking to the position takes up to n steps in the worst case. Setting the four links takes constant time.

Memory
O(1)

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 .

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?

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 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)

Show the answer

The answer is C. The new node's and fields, plus one field in each neighbour: before->next and after->prev. A singly linked list has only two of these.

Lessons you mark show up in the curriculum. This is kept on this device only.