Home  Dsa   Reverse lin ...

Reverse linked list problem and solution in Java

Let's go through reversing a linked list in Java. I’ll show both using built-in LinkedList and implementing your own linked list.


1️⃣ Using Java’s built-in LinkedList

Built-in LinkedList doesn’t have a direct reverse method, but you can do:

import java.util.LinkedList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        // Reverse using Collections.reverse
        Collections.reverse(list);

        System.out.println(list); // Output: [4, 3, 2, 1]
    }
}

✅ Simple, but not “in-place node manipulation”—just rearranges the references internally.


2️⃣ Reversing a Singly Linked List (custom implementation)

Here’s the typical FAANG interview style:

class Node {
    int data;
    Node next;

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

public class LinkedListReversal {
    Node head;

    // Reverse the linked list
    public void reverse() {
        Node prev = null;
        Node curr = head;
        Node next = null;

        while (curr != null) {
            next = curr.next; // store next
            curr.next = prev; // reverse link
            prev = curr;      // move prev forward
            curr = next;      // move curr forward
        }

        head = prev; // new head
    }

    // Print list
    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }

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

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

        list.reverse();

        System.out.print("Reversed: ");
        list.printList();
    }
}

Output:

Original: 1 2 3 4 
Reversed: 4 3 2 1

⚡ Key Points for Interviews

  1. Use three pointers: prev, curr, next.
  2. Update head at the end.
  3. Time Complexity: O(n)
  4. Space Complexity: O(1) (in-place)

Published on: Oct 11, 2025, 11:07 PM  
 

Comments

Add your comment