Walk the list once, flipping each arrow to point backwards. O(1) extra space.
Keep prev (head of the reversed part), curr (node being processed) and nxt (a lifeline to the unprocessed part). Save, flip, advance, repeat.
Algorithm
prev = None,curr = head.- While
curr: savenxt = curr.next. - Flip:
curr.next = prev. - Advance:
prev = curr,curr = nxt. - Return
prev.
- Time
- O(n)
- Space
- O(1)
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: prev = None curr = head while curr: nxt = curr.next # lifeline to the rest of the list curr.next = prev # flip the arrow prev = curr # advance both pointers curr = nxt return prev