Reverse Linked List

Published: (February 27, 2026 at 11:38 AM EST)
3 min read
Source: Dev.to

Source: Dev.to

Objective

  • Reverse a singly linked list in‑place.
  • The last node becomes the first.
  • All next pointers are reversed.
  • Return the new head of the reversed list.

Intuition

A singly linked list node stores a value and a reference to the next node.
If we traverse the list while re‑assigning each node’s next pointer to point to its predecessor, the list becomes reversed.

Approach

Use two pointers while iterating through the list:

PointerMeaning
prevThe node that will become the next of the current node (initially null).
currThe node currently being processed (initially head).

During each iteration:

  1. Store curr.next in a temporary variable (nextTemp).
  2. Set curr.next = prev.
  3. Move prev forward to curr.
  4. Move curr forward to nextTemp.

When curr becomes null, prev points to the new head.

Algorithm (Java)

/**
 * Reverses a singly linked list in‑place.
 *
 * @param head the original head of the list
 * @return the new head after reversal
 */
Node reverseLL(Node head) {
    Node prev = null;      // will become the new head
    Node curr = head;      // current node being processed

    while (curr != null) {
        Node nextTemp = curr.next; // store next node
        curr.next = prev;          // reverse the link
        prev = curr;               // advance prev
        curr = nextTemp;           // advance curr
    }
    // prev is the new head
    return prev;
}

Note: Node is assumed to be a class with at least a Node next field.

Example Walkthrough

Consider the list 10 → 20 → 30 → 40 → null.

StepprevcurrAction
Initialnull10
1102010.next = null
2203020.next = 10
3304030.next = 20
440null40.next = 30

After the loop ends, prev points to 40, yielding the reversed list:

40 → 30 → 20 → 10 → null

Edge Cases

  • Empty list: head == null → the function returns null.
  • Single‑node list: head.next == null → the function returns the same node (no changes needed).

Final Output

The function returns the head of the reversed list, e.g., for the example above the result is 40.

0 views
Back to Blog

Related posts

Read more »

Tales of the Algorhymer: Supply Stacks

Introduction Yet another Computer Science story with a soundtrack! Last time, the story was about a rigged game…https://dev.to/algorhymer/tales-of-the-algorhym...