35. Reverse Linked List
Reverse a singly linked list and return the new head.
Example 1
Input:
head = [1,2,3,4]Output:
[4,3,2,1]Example 2
Input:
head = [7,8]Output:
[8,7]Hint 1
You need three pointers: prev, curr and next.
Approach 1: Recursive
Reverse the rest, then hang the current node at the end.
⏱ Time O(n)💾 Space O(n) stack
Approach 2: Iterative ✅
Flip one arrow per step with prev / curr / next.
⏱ Time O(n)💾 Space O(1)
Reference solution for Iterative (time O(n), space O(1)). Each solution passes every test in all four languages.
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev, curr = None, head
while curr:
nxt = curr.next # remember the rest of the list
curr.next = prev # flip the arrow
prev, curr = curr, nxt
return prevclass Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next; // remember the rest
curr.next = prev; // flip the arrow
prev = curr;
curr = next;
}
return prev;
}
}class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = nullptr, *curr = head;
while (curr) {
ListNode* next = curr->next; // remember the rest
curr->next = prev; // flip the arrow
prev = curr;
curr = next;
}
return prev;
}
};function reverseList(head) {
let prev = null, curr = head;
while (curr) {
const next = curr.next; // remember the rest
curr.next = prev; // flip the arrow
prev = curr;
curr = next;
}
return prev;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Linked Lists.
Run your code to see results here.