algoritmauzmanı
TREN
3.1Singly Linked List
Lesson 3.1.5

Inserting at a position

You have seen inserting at the head and at the end. Inserting at a position sits between the two: the new goes into a given position of the list, for example the third place. To do this you first walk to the node just before that position, then change two links in the right order.

What you will learn
  • That positions count from 0 and why position 0 is inserting at the head
  • In which order the new node is linked in with two assignments
  • Why the list stays unchanged for an invalid position and why the operation is
7 minTime O(n)Memory O(1)C · Java · Python

1Idea

Positions start at 0: position 0 is the place of the first node, position 2 the place of the third. Putting a new node at position 2 means linking it right after the node at position 1. So we start at , walk pos - 1 steps and stop a called prev on that node.

Then come two assignments. First node->next = prev->next: the new node points to the node after prev. Then prev->next = node: prev now points to the new node. The order matters for the same reason as in inserting at the head: if we change prev->next first, we lose the address of the rest of the list.

At position 0 there is no previous node; the operation is inserting at the head, and changes. If the position is negative or larger than the length of the list, the walk falls off to ; then nothing is inserted and the list stays as it was. If the position equals the length of the list, the new node goes at the end.

2Step by step

The drawing inserts 5 at position 2 of the list holding 12, 7 and 3. The result will be 12 → 7 → 5 → 3. At each step the matching line of code lights up.

pos = 2NULL12?0x1a407?0x1a903?0x1b205?0x2c10headprevnode
  1. Start. The list is 12 → 7 → 3 and pos is 2. The new node will go between 7 and 3.
  2. The position is valid and not 0. prev takes the value of and points to the first node.
  3. The loop runs pos - 1 times, that is once. prev moves to 7: the new node will go right after it.
  4. prev is not NULL, so the position is valid. Memory is allocated for the new node and 5 is written into it. It is not linked to the list yet.
  5. node->next = prev->next: the new node points to 3. Right now both 7 and 5 point to 3; the list itself has not changed yet.
  6. prev->next = node: 7 now points to 5. The 7 → 3 link has been replaced by 7 → 5.
  7. Result: 12 → 7 → 5 → 3 → NULL. did not change; only two fields were updated.

struct Node {    int data;    struct Node* next;}; void insertAt(struct Node** head, int pos, int value) {    if (pos < 0) return;                  // invalid position    if (pos == 0) {                       // insert at the head        struct Node* node = malloc(sizeof(struct Node));        node->data = value;        node->next = *head;        *head = node;        return;    }    struct Node* prev = *head;    for (int i = 0; i < pos - 1 && prev != NULL; i++)        prev = prev->next;    if (prev == NULL) return;             // position is past the end    struct Node* node = malloc(sizeof(struct Node));    node->data = value;    node->next = prev->next;              // this line first    prev->next = node;                    // then this one}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} Node insertAt(Node head, int pos, int value) {    if (pos < 0) return head;             // invalid position    if (pos == 0) {                       // insert at the head        Node node = new Node(value);        node.next = head;        return node;    }    Node prev = head;    for (int i = 0; i < pos - 1 && prev != null; i++)        prev = prev.next;    if (prev == null) return head;        // position is past the end    Node node = new Node(value);    node.next = prev.next;                // this line first    prev.next = node;                     // then this one    return head;}
class Node:    def __init__(self, data):        self.data = data        self.next = None def insert_at(head, pos, value):    if pos < 0:  # invalid position        return head    if pos == 0:  # insert at the head        node = Node(value)        node.next = head        return node    prev = head    i = 0    while prev is not None and i < pos - 1:        prev = prev.next        i += 1    if prev is None:  # position is past the end        return head    node = Node(value)    node.next = prev.next  # this line first    prev.next = node       # then this one    return head

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

3Complexity

Time
O(n)

Reaching the previous node means passing pos - 1 nodes. In the worst case, a position near the end, that is n steps.

Memory
O(1)

Apart from the new node, only one helper pointer and a counter are used.

The linking itself is two assignments and takes . The walk decides the cost. If you already hold a pointer to the previous node, the insertion is O(1).

4Common mistake

The most common mistake is writing the two assignments in reverse:

prev->next = node;node->next = prev->next;   // now the new node itself

After the first line prev->next already points to the new node. The second line writes the new node into its own field, so the node points to itself. The address of 3 and everything after it is stored nowhere. Code that traverses this list also runs forever.

5Try it

In the list 12 → 7 → 3, what happens if you insert 9 at position 3?

Show the answer

The answer is B. prev walks 2 steps and stops on the last node (3). node->next takes 3's next field, which is , and the new node is linked at the end. At position 4 the walk would fall off to NULL and the list would not change.

Why is position 0 handled separately?

Show the answer

The answer is A. If the new node goes first, there is no node to link it after. Instead the new node points to the old first node and is moved to the new node. That is exactly inserting at the head.

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