0
0
JavaProgramBeginner · 2 min read

Java Program to Reverse Linked List with Output

To reverse a linked list in Java, use a loop to change each node's next pointer to the previous node, like this: while (current != null) { Node next = current.next; current.next = prev; prev = current; current = next; }.
📋

Examples

Input1 -> 2 -> 3 -> null
Output3 -> 2 -> 1 -> null
Input10 -> 20 -> null
Output20 -> 10 -> null
Inputnull
Outputnull
🧠

How to Think About It

To reverse a linked list, think of walking through the list from start to end and flipping the direction of each arrow (pointer) so it points backward instead of forward. You keep track of the previous node to link the current node back to it, and move forward until you reach the end.
📐

Algorithm

1
Start with three pointers: previous as null, current as head, and next as null.
2
While current is not null, do the following:
3
Save current's next node in next.
4
Change current's next pointer to previous.
5
Move previous to current.
6
Move current to next.
7
After the loop, previous will be the new head of the reversed list.
💻

Code

java
class Node {
    int data;
    Node next;
    Node(int data) { this.data = data; this.next = null; }
}

public class ReverseLinkedList {
    static Node reverse(Node head) {
        Node prev = null;
        Node current = head;
        while (current != null) {
            Node next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }

    static void printList(Node head) {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " -> ");
            temp = temp.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);

        System.out.print("Original list: ");
        printList(head);

        head = reverse(head);

        System.out.print("Reversed list: ");
        printList(head);
    }
}
Output
Original list: 1 -> 2 -> 3 -> null Reversed list: 3 -> 2 -> 1 -> null
🔍

Dry Run

Let's trace the list 1 -> 2 -> 3 -> null through the reverse function.

1

Initialize pointers

prev = null, current = Node(1)

2

First iteration

next = Node(2), current.next = prev (null), prev = Node(1), current = Node(2)

3

Second iteration

next = Node(3), current.next = prev (Node(1)), prev = Node(2), current = Node(3)

4

Third iteration

next = null, current.next = prev (Node(2)), prev = Node(3), current = null

5

End loop

current is null, return prev as new head (Node(3))

prevcurrentnextcurrent.next
nullNode(1)Node(2)null
Node(1)Node(2)Node(3)Node(1)
Node(2)Node(3)nullNode(2)
💡

Why This Works

Step 1: Track previous and current nodes

We keep a prev pointer to remember the reversed part and a current pointer to process nodes one by one.

Step 2: Reverse the link

For each node, we change its next pointer to point to prev, flipping the direction.

Step 3: Move forward

We move prev and current forward to continue reversing until all nodes are processed.

🔄

Alternative Approaches

Recursive reversal
java
class Node {
    int data;
    Node next;
    Node(int data) { this.data = data; this.next = null; }
}

public class ReverseLinkedList {
    static Node reverseRecursive(Node head) {
        if (head == null || head.next == null) return head;
        Node rest = reverseRecursive(head.next);
        head.next.next = head;
        head.next = null;
        return rest;
    }

    static void printList(Node head) {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " -> ");
            temp = temp.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);

        System.out.print("Original list: ");
        printList(head);

        head = reverseRecursive(head);

        System.out.print("Reversed list: ");
        printList(head);
    }
}
Uses recursion to reverse links, simpler code but uses extra stack space.
Using stack
java
import java.util.Stack;

class Node {
    int data;
    Node next;
    Node(int data) { this.data = data; this.next = null; }
}

public class ReverseLinkedList {
    static Node reverseWithStack(Node head) {
        if (head == null) return null;
        Stack<Node> stack = new Stack<>();
        Node temp = head;
        while (temp != null) {
            stack.push(temp);
            temp = temp.next;
        }
        Node newHead = stack.pop();
        temp = newHead;
        while (!stack.isEmpty()) {
            temp.next = stack.pop();
            temp = temp.next;
        }
        temp.next = null;
        return newHead;
    }

    static void printList(Node head) {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " -> ");
            temp = temp.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);

        System.out.print("Original list: ");
        printList(head);

        head = reverseWithStack(head);

        System.out.print("Reversed list: ");
        printList(head);
    }
}
Uses extra memory for stack, easier to understand but less efficient.

Complexity: O(n) time, O(1) space

Time Complexity

The algorithm visits each node once, so the time is linear in the number of nodes, O(n).

Space Complexity

It uses only a few pointers and reverses the list in place, so space is O(1).

Which Approach is Fastest?

The iterative method is fastest and uses constant space, while recursion and stack methods use extra memory.

ApproachTimeSpaceBest For
Iterative reversalO(n)O(1)Efficient in-place reversal
Recursive reversalO(n)O(n)Cleaner code but uses stack memory
Using stackO(n)O(n)Easy to understand but uses extra memory
💡
Always keep track of the next node before changing links to avoid losing the rest of the list.
⚠️
Forgetting to save the next node before reversing the link causes loss of the remaining list.