5. Reverse Linked List
easyAsked at RedisReverse a singly linked list in place; Redis uses it as a warm-up before diving into Redis list internals like the quicklist and listpack.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the head of a singly linked list, reverse the list and return the new head. Solve both iteratively and (optionally) recursively.
Constraints
0 <= nodes <= 5000-5000 <= Node.val <= 5000
Examples
Example 1
head = [1,2,3,4,5][5,4,3,2,1]Example 2
head = [][]Approaches
1. Stack rebuild
Push all nodes to a stack then pop.
- Time
- O(n)
- Space
- O(n)
const stack = [];
let cur = head;
while (cur) { stack.push(cur); cur = cur.next; }
const dummy = new ListNode();
let tail = dummy;
while (stack.length) { tail.next = stack.pop(); tail = tail.next; }
tail.next = null;
return dummy.next;Tradeoff:
2. Iterative pointer flip
Walk the list keeping prev/cur/next and re-point each node. This is exactly how Redis lists used to work before quicklist replaced the raw linked list.
- Time
- O(n)
- Space
- O(1)
function reverseList(head) {
let prev = null, cur = head;
while (cur) {
const next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}Tradeoff:
Redis-specific tips
Redis interviewers love a quick aside on quicklist (linked list of listpacks) here; show you know Redis dropped raw doubly-linked lists for cache locality.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Reverse Linked List and other Redis interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →