Insertion at the head of Linked List
Pattern: Traversal and dummy nodes
Make a new node whose next is the old head, and return it. One step, O(1), and it works on an empty list too.
The problem
Given the head of a singly linked list and a value X, insert a new node holding X at the front and return the new
head. For example, 1 → 2 → 3 with X = 0 becomes 0 → 1 → 2 → 3, and an empty list with X = 7 becomes 7.
The function name insertAtHead matches the takeUforward practice page. Use the link above for the exact statement and
limits.
Think first
- Which node will come after the new one?
- Do you need to walk the list at all?
- What should the function return?
Hints
Brute force, and why it fails
Rebuilding the list with the value in front costs O(n). Linking one node costs O(1).
The key insight
The front is the one place in a singly linked list you can change without walking. That is why stacks are often built on linked lists.
Dry run
The list is 1 → 2 → 3 and X = 0.
The plan
node = new node(X)
node.next = head
return node
Complexity
- Time
O(1)- Space
O(1)
One node is created and one pointer is set.
Edge cases
- Empty list: the result is just
X. - One node: two nodes.
Xequal to an existing value is fine.
I've built my logic, show the code
Java
class Solution {
public ListNode insertAtHead(ListNode head, int X) {
ListNode node = new ListNode(X);
node.next = head; // the old head comes after the new node
return node;
}
}C++
class Solution {
public:
ListNode* insertAtHead(ListNode* head, int X) {
ListNode* node = new ListNode(X);
node->next = head; // the old head comes after the new node
return node;
}
};Python
from lib import ListNode
class Solution:
def insertAtHead(self, head: ListNode, X: int) -> ListNode:
return ListNode(X, head) # the old head comes after the new nodeCommon mistakes
- Returning the old head, which leaves the new node unreachable.
- Walking to the end first, which is not needed.
- Setting
head.next = node, which inserts after the head instead.