15. Reverse Linked List
easyAsked at GitLabReverse a singly linked list in place and return the new head.
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. Do it iteratively or recursively.
Constraints
0 <= nodes <= 5000-5000 <= 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 values onto a stack, pop into a new list. Two passes, extra memory.
- Time
- O(n)
- Space
- O(n)
const st=[]; let n=head;
while (n){ st.push(n.val); n=n.next; }
let dummy={next:null}, t=dummy;
while (st.length){ t.next={val:st.pop(), next:null}; t=t.next; }
return dummy.next;Tradeoff:
2. Three-pointer in place
Walk once with prev/curr/next, rewiring each next pointer backwards.
- Time
- O(n)
- Space
- O(1)
function reverseList(head){
let prev = null, curr = head;
while (curr){
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}Tradeoff:
GitLab-specific tips
GitLab interviewers use this as a warm-up to test pointer hygiene before pushing into harder graph problems involving merge-request review chains.
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 GitLab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →