Linked List Easy
Reverse a Linked List: Solution and Approach
Reverse a singly linked list and return the new head.
Similar questions reported in: TCS, Infosys, Wipro, Capgemini, Amazon, Cognizant
Example
- Input:
- 1 → 2 → 3 → 4 → 5
- Output:
- 5 → 4 → 3 → 2 → 1
Brute force first
Copy the values into an array and rebuild the list backwards. This uses O(n) extra space.
The better idea
Walk the list once and turn each next pointer around. Keep three pointers: prev, curr and the saved next node.
Steps
- Set prev = null and curr = head.
- While curr is not null: save nxt = curr.next, set curr.next = prev, then move prev = curr and curr = nxt.
- When the loop ends, prev is the new head.
Code
def reverse_list(head):
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev, curr = curr, nxt
return prevpublic ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nxt = curr.next;
curr.next = prev;
prev = curr;
curr = nxt;
}
return prev;
}Complexity
Time: O(n)
Space: O(1)
Edge cases to test
- An empty list (head is null): return null.
- A single node: it is returned unchanged.
Interview follow-up: Interviewers often ask for the recursive version too. It uses O(n) stack space.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.