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.
| step | prev | cur | list so far |
|---|---|---|---|
| start | null | 1 | 1 → 2 → 3 |
| 1 | 1 | 2 | 1 ← and 2 → 3 |
| 2 | 2 | 3 | 1 ← 2 and 3 |
| 3 | 3 | null | 1 ← 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.nextbefore 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
- Reverse Linked Listeasyguide ready
- Plus One Linked Listmediumguide ready
- Delete nodes which have a greater value on right sidemediumguide ready
- Reverse Nodes in k-Grouphardguide ready