Back to All Questions
Reverse a Linked List
Netflix
Linked List
Two Pointers
Given the head of a singly linked list, reverse the list, and return the reversed list's head.
Example:
Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]
Solution Walkthrough
The iterative approach reverses the list in place by walking through it once and flipping each node's next pointer to point backward instead of forward.
- Keep three pointers:
prev(initiallynull),curr(initiallyhead), and a temporarynext. - While
curris notnull:- Save
curr.nextintonextbefore you overwrite it. - Point
curr.nextback toprev. - Move
prevup tocurr, andcurrup tonext.
- Save
- When the loop ends,
currisnullandprevis sitting on the new head — return it.
This runs in O(n) time with O(1) extra space, since every node is visited exactly once and no new list is allocated.
1 2 3 4 5 6 7 8 9 10 11 12 13
Related Algorithms