Insertion at the head of Linked List
EasyPoint the new node at the old head
Problem
Given the head of a singly linked list and a value, insert a new node with that value at the front so it becomes the new head. Return the new head.
Make a new node point at the old first node, then call it the new first.
The idea
Create the node, set its next to the current head, and return it as the new head. Order matters: link the new node first, because reassigning the head before doing so loses the rest of the list.
The trick
- newNode.next = head, then head = newNode. Never the other way round.
- O(1), and it works on an empty list without a special case.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — head = [2, 3, 4], val = 1 Values: 2, 3, 4.
1newNode = Node(val)2newNode.next = head3head = newNode4return headInput
- array
- [2, 3, 4]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Example
- Input:
- head = [2, 3, 4], val = 1
- Output:
- [1, 2, 3, 4]
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.