Learn / Linked lists

Reversal

Reversing a list turns every arrow around, using three pointers: prev, cur and next. It is a building block: reverse a part to walk the list backwards, reverse groups of k nodes, or reverse, process from the right, and reverse back.

How to recognise it

  • The question asks to reverse a list, or part of it, or groups of k nodes, in place.
  • The rule depends on what is to the right of each node (a larger value later, a carry from the end).
  • You need to compare the list with itself backwards (palindrome checks).

The idea in one picture

Picture people in a line, each pointing at the person in front. To reverse the line, walk along it and make each person point at the one behind instead. You need to remember who is behind (prev), who you are turning (cur), and who is next (next), because once cur turns around, it no longer points forward.

stepprevcurlist so far
startnull11 → 2 → 3
1121 ← and 2 → 3
2231 ← 2 and 3
33null1 ← 2 ← 3

Template

prev = null, cur = head
while cur is not null:
    next = cur.next
    cur.next = prev
    prev = cur
    cur = next
return prev

Reverse, process, reverse back

When each node's fate depends on what lies to its right, reverse the list first. Now "to the right" becomes "already seen", which is easy to track in one pass. Reverse again at the end to restore the order.

Reversing a group in the middle

For a group of k nodes between groupPrev and groupNext, start prev at groupNext instead of null. After reversing the group, its old first node already points to groupNext, so only groupPrev.next needs fixing.

Common mistakes

  • Flipping cur.next before saving it.
  • Returning head, which is now the last node.
  • Reversing a final short group in Reverse Nodes in k-Group.
  • Losing the link from the previous group to the reversed one.

Problems

0 of 4 solved

Check yourself

In the reversal loop, why save cur.next before changing cur.next?

After the loop ends, which pointer holds the new head?

In Reverse Nodes in k-Group, what happens to a final group with fewer than k nodes?