3.1Singly Linked List
- 3.1.1What is a singly linked list?
- 3.1.2Creating a singly linked list
- 3.1.3Traversal
- 3.1.4Inserting at the end
- 3.1.5Inserting at a position
- 3.1.6Inserting at the head
- 3.1.7Deleting from the end
- 3.1.8Deleting from the head
- 3.1.9Deleting from the middle
- 3.1.10Searching for a value
- 3.1.11Reversing a linked list (iterative)
- 3.1.12Reversing a linked list (recursive)
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 node 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.
- 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 next assignments
- Why the list stays unchanged for an invalid position and why the operation is O(n)
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 head, walk pos - 1 steps and stop a pointer 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 head changes. If the position is negative or larger than the length of the list, the walk falls off to NULL; 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.
- Start. The list is 12 → 7 → 3 and
posis 2. The new node will go between 7 and 3. - The position is valid and not 0.
prevtakes the value of head and points to the first node. - The loop runs
pos - 1times, that is once.prevmoves to 7: the new node will go right after it. previs 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.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.prev->next = node: 7 now points to 5. The 7 → 3 link has been replaced by 7 → 5.- Result: 12 → 7 → 5 → 3 → NULL. head did not change; only two next 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 headThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Reaching the previous node means passing pos - 1 nodes. In the worst case, a position near the end, that is n steps.
Apart from the new node, only one helper pointer and a counter are used.
The linking itself is two assignments and takes O(1). 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 itselfAfter the first line prev->next already points to the new node. The second line writes the new node into its own next 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?
The answer is B. prev walks 2 steps and stops on the last node (3). node->next takes 3's next field, which is NULL, 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.
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 NULL, 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?
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 head is moved to the new node. That is exactly inserting at the head.
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 head 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.