Reverse Linked List
Difficulty: Easy
Given the head of a singly linked list (each node points only to the next one), reverse the list and return the new head.
Don't just relabel the values — rewire each node's pointer to point at the node that came before it.
Examples
Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Input: head = [1, 2]
Output: [2, 1]
Input: head = []
Output: []
An empty list reversed is still empty.
Constraints
The number of nodes is between 0 and 5000.
-5000 <= Node.val <= 5000
Approach
Flip one pointer at a time as you walk the list. Order matters: once you overwrite a node's next pointer, you can't reach the rest of the list unless you saved that reference first.
Carry three references: the previous node (initially null), the current node, and (briefly) the next node. At each step, point the current node backward, then move all three one step forward.
You can also do it recursively: reverse the rest of the list first, then fix the one link at the front.
Solutions
Recursive Reversal
Trust that the recursive call reverses everything after the current node, then fix the link between the current node and the rest.
After the rest is reversed, the node right after the current one is the last node of that reversed piece. Point it back at the current node, and clear the current node's forward pointer.
It reads nicely, but every call stays on the stack until the end of the list, so it uses memory proportional to the list's length.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function reverseList(head) {
if (head === null || head.next === null) {
return head;
}
const newHead = reverseList(head.next);
// head.next is currently the last node of the already-reversed rest.
// Make it point back at head, then clear head's old forward link.
head.next.next = head;
head.next = null;
return newHead;
}Time: O(n) · Space: O(n) — call stack depth equals list length
Optimal — Iterative Pointer Rewiring
Walk the list once with a "previous" pointer that starts at null. At each node, save its next pointer, point the node back at "previous", then move "previous" and "current" one step forward.
When "current" runs off the end, "previous" is on the old last node — the new head.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function reverseList(head) {
let prev = null;
let curr = head;
while (curr !== null) {
const next = curr.next; // save before we overwrite curr.next
curr.next = prev; // flip the pointer
prev = curr; // advance prev
curr = next; // advance curr
}
return prev; // prev now points at the old tail — the new head
}Time: O(n) · Space: O(1)