Reversal
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Reversing a linked list means turning every link around so the last item becomes the first. You do it in one pass, flipping each link and remembering where you came from, without making a copy of the list.
Practical use cases
- Web app: Show newest activity first. Events were appended in time order, oldest first, but the Recent Activity panel must show the newest on top. Instead of building a second list, the code reverses the chain in one pass and renders it directly. The panel is ready after one loop over the items.
- Web app: Reading a long thread in reverse. A comments page lets readers toggle between Oldest first and Newest first. Reversing the existing chain in place flips the order without copying thousands of comments, so the toggle feels instant and uses no extra memory.
- System: Palindrome checks and history replay. A tool that checks whether a chain of characters reads the same both ways reverses its second half and compares it with the first. A history viewer that stores steps oldest first does the same flip to replay them from the most recent step, with no copy of the data.
The story: The Train That Turned Around
At the old railway yard, a train of four coaches (A → B → C → D) had to go back the way it came. There was no turntable. The engineer, Mr. Bhaskar, had a plan: flip the coupling between coaches one at a time.
But there was a danger. Each coach only knew about the coach in front of it. If he unhooked B from C, nobody would remember where C was, and the rest of the train would be lost forever.
So he used three helpers: one standing at the previous coach, one at the current, and one holding a note of the next. Note the next. Flip the coupling backwards. Step everyone forward. Repeat. When he finished, D led the way: D → C → B → A.
How to spot this problem, and where you need it
The data arrives in one order but you need it in the opposite order, and you want to avoid copying everything into a new list or running slow nested loops.
Signs you need it
- The requirement says "reverse", "newest first", "last to first", or "read it backward".
- Your list only has next links, so you cannot walk backward, yet you need the end first.
- Another task such as checking a palindrome or adding two numbers stored digit by digit needs the second half flipped.
Where to use it in a project
- Toggling sort order of feeds, comments or logs held as chains.
- Helper step inside palindrome checks or digit-by-digit arithmetic on linked lists.
- Reordering undo or navigation history when you switch direction.
The solution
Walk through the list with three markers: previous (starts empty), current and next. At each step, first remember the next box, then make the current box point back to previous, then move previous and current one step forward. When current runs off the end, previous is the new head. One pass, no extra list.
Payoff: Before: copying 50,000 items into a new list. After: one pass and a few markers, no extra memory.
Explain it like I am 8
Imagine kids in a line, each holding the hand of the child in front. To reverse the line, one by one, each child lets go of the front hand and grabs the hand of the child behind instead. But first they must remember who was in front, or that child gets lost!
How it works, step by step
- Start with
prev = nullandcurrent = head. The first node will become the tail, so it points at nothing. - Save the next node.
next = current.next. This is the safety note. - Flip the pointer.
current.next = prev. - Step forward.
prev = current,current = next. When current is null,previs the new head.
The code in four languages
PHP
<?php
class Node {
public function __construct(public $val, public ?Node $next = null) {}
}
function reverseList(?Node $head): ?Node {
$prev = null;
$current = $head;
while ($current !== null) {
$next = $current->next; // 1. remember the rest of the train
$current->next = $prev; // 2. flip the coupling backwards
$prev = $current; // 3. step forward
$current = $next;
}
return $prev; // the old tail is the new head
}
$head = new Node(1, new Node(2, new Node(3, new Node(4)))); // 1 -> 2 -> 3 -> 4
$out = [];
for ($n = reverseList($head); $n !== null; $n = $n->next) $out[] = $n->val;
echo implode(' -> ', $out), "\n"; // 4 -> 3 -> 2 -> 1JavaScript
class Node {
constructor(val, next = null) { this.val = val; this.next = next; }
}
function reverseList(head) {
let prev = null;
let current = head;
while (current !== null) {
const next = current.next; // 1. remember the rest of the train
current.next = prev; // 2. flip the coupling backwards
prev = current; // 3. step forward
current = next;
}
return prev; // the old tail is the new head
}
const head = new Node(1, new Node(2, new Node(3, new Node(4)))); // 1 -> 2 -> 3 -> 4
const out = [];
for (let n = reverseList(head); n !== null; n = n.next) out.push(n.val);
console.log(out.join(' -> ')); // 4 -> 3 -> 2 -> 1Java
public class Main {
static class Node {
int val;
Node next;
Node(int val, Node next) { this.val = val; this.next = next; }
}
static Node reverseList(Node head) {
Node prev = null;
Node current = head;
while (current != null) {
Node next = current.next; // 1. remember the rest of the train
current.next = prev; // 2. flip the coupling backwards
prev = current; // 3. step forward
current = next;
}
return prev; // the old tail is the new head
}
static void show(Node head) {
StringBuilder sb = new StringBuilder();
for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" -> ");
System.out.println(sb + "null");
}
public static void main(String[] args) {
Node head = new Node(1, new Node(2, new Node(3, new Node(4, null))));
show(head); // 1 -> 2 -> 3 -> 4 -> null
show(reverseList(head)); // 4 -> 3 -> 2 -> 1 -> null
}
}Go
package main
import "fmt"
type Node struct {
val int
next *Node
}
func reverseList(head *Node) *Node {
var prev *Node
current := head
for current != nil {
next := current.next // 1. remember the rest of the train
current.next = prev // 2. flip the coupling backwards
prev = current // 3. step forward
current = next
}
return prev // the old tail is the new head
}
func show(head *Node) {
for c := head; c != nil; c = c.next {
fmt.Print(c.val, " -> ")
}
fmt.Println("nil")
}
func main() {
head := &Node{1, &Node{2, &Node{3, &Node{4, nil}}}}
show(head) // 1 -> 2 -> 3 -> 4 -> nil
show(reverseList(head)) // 4 -> 3 -> 2 -> 1 -> nil
}Time: O(n) · Extra space: O(1). One pass, and only three pointers are used, no matter how long the list is.
Watch out for
- Flipping
current.nextbefore saving it. The rest of the list is lost. - Returning
headinstead ofprev. After reversing, the old head is the tail.
Quick check
- Why do we save current.next before flipping?
- To save memory
- Otherwise we lose the rest of the list
- It is faster
- When the loop ends, which pointer is the new head?
- current
- next
- prev
- What is the extra memory used?
- O(1)
- O(n)
- O(n²)