Reverse Linked List - Problem
Given the head of a singly linked list, your task is to reverse the entire list and return the new head of the reversed list.
Imagine you have a chain of nodes where each node points to the next one: 1 → 2 → 3 → 4 → 5 → NULL. After reversing, it should become: 5 → 4 → 3 → 2 → 1 → NULL.
What you need to do:
- Take a linked list as input
- Reverse the direction of all pointers
- Return the new head (which was originally the tail)
- Handle edge cases like empty lists or single nodes
This is a fundamental problem that tests your understanding of pointer manipulation and is frequently asked in technical interviews!
Input & Output
example_1.py — Basic Reversal
$
Input:
[1,2,3,4,5]
›
Output:
[5,4,3,2,1]
💡 Note:
The original list 1→2→3→4→5→NULL becomes 5→4→3→2→1→NULL after reversing all the pointer directions.
example_2.py — Two Node List
$
Input:
[1,2]
›
Output:
[2,1]
💡 Note:
A simple two-node list 1→2→NULL becomes 2→1→NULL. The first node now points to NULL and second points to first.
example_3.py — Single Node
$
Input:
[1]
›
Output:
[1]
💡 Note:
A single node list remains unchanged since there are no pointers to reverse. The node still points to NULL.
Visualization
Tap to expand
Understanding the Visualization
1
Setup the Formation
Position three key people: Previous (start), Current (first person), and Next (second person)
2
Save the Chain
Next person remembers who comes after them before the current person turns around
3
Turn Around
Current person turns to face and hold hands with the Previous person
4
Move Forward
Everyone shifts positions: Previous becomes Current, Current becomes Previous, Next becomes Current
5
Repeat the Dance
Continue this pattern until everyone has turned around - the last person is now the leader!
Key Takeaway
🎯 Key Insight: We only need to track three consecutive nodes at any time. By carefully managing these three pointers (prev, curr, next), we can reverse all links in a single pass without using extra space for data storage.
Time & Space Complexity
Time Complexity
O(n)
We traverse the list once to build array O(n), reverse array O(n), then build new list O(n), giving us O(3n) = O(n)
✓ Linear Growth
Space Complexity
O(n)
We need extra space for the array to store all node values, plus space for the new linked list nodes
⚡ Linearithmic Space
Constraints
- The number of nodes in the list is the range [0, 5000]
- -5000 ≤ Node.val ≤ 5000
- The linked list is guaranteed to be valid
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code