Medium Logical Thinking Java

Reverse a Linked List in Java

Reverse a singly linked list and return the new head.

  • TimeO(n)
  • SpaceO(1) with a loop, O(n) with recursion
  • Hints3
  • Read2 min
Quick answer

To reverse a linked list in Java, walk through it with three pointers: prev, current and next. At each node, save the next node, point current.next back to prev, then move both pointers one step forward. When current is null, prev is the new head. It takes O(n) time and O(1) space.

Linked listPointersRecursion
1

Problem statement

You get the head of a singly linked list. Reverse a linked list in Java by changing its links, and return the new head. Do not copy the values into an array.

1 -> 2 -> 3 -> 4 -> null must become 4 -> 3 -> 2 -> 1 -> null.

Input

The head node of a singly linked list. It may be null.

Output

The head node of the reversed list.

Examples

Example 1
Input1 -> 2 -> 3 -> 4 -> null
Output4 -> 3 -> 2 -> 1 -> null

Each arrow now points to the node before it.

Example 2
Input9 -> null
Output9 -> null

A list with one node does not change.

Constraints

  • 0 <= number of nodes <= 10^5
  • The list has no loop
2

Think before you code

Reveal the questions to ask yourself first
  • If you change current.next, how will you reach the rest of the list?
  • What should the old first node point to at the end?
  • Which pointer holds the new head when the loop ends?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Save current.next in a variable before you change it.
2 Hint 2
Point current.next to prev, which starts as null.
3 Hint 3
Move prev to current and current to the saved node. Return prev.
4

Approach

Reveal the step-by-step approach
  1. Set prev = null and current = head.
  2. While current is not null:
    • Save next = current.next.
    • Turn the arrow: current.next = prev.
    • Move on: prev = current, then current = next.
  3. Return prev.

The order of these four lines matters. If you turn the arrow before saving next, the rest of the list is lost. For how a node class works, read classes and objects.

5

Dry run

Walk through the example step by step

Reversing 1 -> 2 -> 3 -> 4:

step | current | reversed part (prev)     | still to do
-----+---------+--------------------------+-----------------
0    | 1       | null                     | 1 -> 2 -> 3 -> 4
1    | 2       | 1 -> null                | 2 -> 3 -> 4
2    | 3       | 2 -> 1 -> null           | 3 -> 4
3    | 4       | 3 -> 2 -> 1 -> null      | 4
4    | null    | 4 -> 3 -> 2 -> 1 -> null | nothing
6

Solution

Reveal the full Java solution
Solution.java
public class ReverseLinkedList {
    static class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
        }
    }

    public static Node reverse(Node head) {
        Node prev = null;
        Node current = head;
        while (current != null) {
            Node next = current.next; // save the rest of the list
            current.next = prev;      // turn the arrow around
            prev = current;
            current = next;
        }
        return prev; // the old last node is the new head
    }

    static Node build(int... values) {
        Node dummy = new Node(0);
        Node tail = dummy;
        for (int v : values) {
            tail.next = new Node(v);
            tail = tail.next;
        }
        return dummy.next;
    }

    static String show(Node head) {
        StringBuilder sb = new StringBuilder();
        for (Node n = head; n != null; n = n.next) {
            sb.append(n.data).append(" -> ");
        }
        return sb.append("null").toString();
    }

    public static void main(String[] args) {
        System.out.println(show(reverse(build(1, 2, 3, 4))));
        // 4 -> 3 -> 2 -> 1 -> null
        System.out.println(show(reverse(build(9)))); // 9 -> null
        System.out.println(show(reverse(null)));     // null
    }
}

This reverse a linked list in Java program changes one arrow per step. No new nodes are made during the reversal, so the extra space stays O(1). The empty list needs no special check: the loop never runs and prev is null.

Reverse a linked list in Java using recursion

Let recursion reverse everything after the head. Then make the next node point back.

static Node reverseRecursive(Node head) {
    if (head == null || head.next == null) {
        return head;
    }
    Node newHead = reverseRecursive(head.next);
    head.next.next = head; // the next node now points back to us
    head.next = null;      // cut the old arrow
    return newHead;
}

It gives the same result. Each node uses one method call, so the space is O(n) and a very long list can cause a StackOverflowError. Prefer the loop for large lists.

Reverse a doubly linked list in Java

To reverse a singly linked list in Java you change one link per node. A doubly linked list has two, so you swap them.

static class DNode {
    int data;
    DNode prev, next;

    DNode(int data) {
        this.data = data;
    }
}

static DNode reverseDoubly(DNode head) {
    DNode newHead = head;
    DNode current = head;
    while (current != null) {
        DNode next = current.next;
        current.next = current.prev; // swap the two links
        current.prev = next;
        newHead = current;
        current = next;
    }
    return newHead;
}

For 1 <-> 2 <-> 3, reading forward from the new head gives 3 2 1. Reading back from the end gives 1 2 3, so both directions are correct.

With the built-in LinkedList

In a project, Collections.reverse(list) is the reverse a linked list in Java code you would use with java.util.LinkedList. This problem wants the pointer version. See ArrayList vs LinkedList for how Java's list is stored.

Practise next: valid parentheses, DSA interview questions and the Java full stack course.

TimeO(n)
SpaceO(1) with a loop, O(n) with recursion
7

Review before the interview

Common mistakes

  • Changing current.next before saving it, which loses the rest of the list.
  • Returning head. It is now the last node. Return prev.
  • In recursion, forgetting head.next = null, which leaves a loop in the list.

Edge cases to test

  • An empty list returns null.
  • One node returns the same node.
  • Two nodes is a good small test for both versions.

Interview follow-ups

  • How would you reverse only the part between two positions?
  • How would you reverse the list in groups of k?
  • How can reversing help you check if a linked list is a palindrome?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us