Reverse segments of a singly linked list by manipulating pointers — O(1) extra memory.
before: 1 -> 2 -> 3 -> 4 -> 5 -> None
iteratively:
save next, flip cur.next to prev, advance prev/cur
after: 5 -> 4 -> 3 -> 2 -> 1 -> None
def reverse(head):
prev, cur = None, head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev
next before the swap — if you overwrite cur.next first, the rest of the list is lost.A train reversing engine order by detaching cars in pairs and re-attaching them in the opposite direction, one at a time.
Interview tip: Always use three pointers: prev, cur, nxt. The moment you forget to set
cur.next = prevBEFORE updatingprev, the list loops back.