CodeArchon

easyLinked ListAmazonGoogleMicrosoft

Reverse Chain

A singly linked chain of beads. Rebuild it so the last bead becomes the first and all arrows face backward.

Given the head of a singly linked list, reverse it and return the new head.

Choose approach

1
curr
2
3
4
5
nil
prev
1/12
Narrationstep 1 of 12

prev = null, curr = head. Walk the list; at each node flip its arrow backward.

1def reverse_chain(head):
2 prev, curr = None, head
3 while curr:
4 nxt = curr.next
5 curr.next = prev
6 prev = curr
7 curr = nxt
8 return prev
Variables
prev=null
curr=1

How to think about it

  1. Three pointers suffice; no auxiliary list.
  2. Save next first — otherwise the forward link is lost after the flip.
  3. Walk ends when curr is null; prev holds the new head.

Edge cases to catch in interview

  • Empty list → null.
  • Single node → unchanged.
  • Two nodes → swap neighbours.

Examples

Example 1[5,4,3,2,1]
{"values":[1,2,3,4,5]}
Example 2[]
{"values":[]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed