Linked List Insertion At Beginning

easy

You are given the head of a singly linked list and an integer x. Insert x at the very beginning of the list and return the head of the modified list.

The new value always becomes the first node, sitting in front of every existing node. The rest of the list keeps its exact order and values — only the front of the list changes.

Because the front of a list is directly reachable through head, this can be done in constant time without walking the list.

Hints

Where does a new first element have to point so the rest of the list stays attached?
You only ever create one node — nothing already in the list needs to move.
Make a node for x, set its next to the current head, and return that node as the new head — all O(1).

Common doubts

No. The front is directly reachable through head, so insertion is a single pointer move — O(1).
The new node's next becomes null and it becomes a one-node list — the same code handles it with no special case.
No. Insertion at the beginning is about position, not value — x always becomes the new first node, even if it duplicates an existing value.

Interview follow-ups

Walk to the last node and set its next to the new node — O(n), unless you keep a tail pointer, which makes it O(1).
Advance k-1 steps from the head, then splice the new node between the (k-1)-th node and its successor.

Fun facts

  • Inserting at the head is exactly the push of a stack — a linked list gives you an O(1) stack for free.
  • Immutable/persistent lists (like Lisp's cons cells) are built almost entirely on this head-prepend operation.

Asked at

AmazonMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: head = [2, 10], x = 1
Output: 1 -> 2 -> 10
The value 1 is placed at the front, so it becomes the new head; 2 -> 10 follow unchanged.
Example 2
Input: head = [2, 3, 4, 5], x = 1
Output: 1 -> 2 -> 3 -> 4 -> 5
1 is inserted at the beginning, ahead of the existing 2 -> 3 -> 4 -> 5.
Constraints

- 1 <= number of nodes <= 10^5 - 1 <= node value <= 10^3 - 1 <= x <= 10^3

Solve this problem →