Java Program to Reverse a linked list

Introduction

The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.

Problem Statement

In this question, we are given a singly linked list. We have to reverse the given list.

Problem Statement Understanding

Let’s try to understand this problem statement with help of examples.

Suppose the given linked list is:

Here we have to reverse this linked list. So to reverse the linked list, we will have to change the links of all the nodes of linked list such that:

  • 1→7 will become 7→1.
  • 7→15 becomes 15→7.
  • 15→27 becomes 27→15.

27 will now become the new head of the linked list. So, the final reverse linked list will be

Input:

Output:

Explanation: The input list has been reversed.

This question is not a very complex one. We have to make use of list traversal in the question. The only change will be that we will be changing the links of each node.

Approach (Iterative)

The approach is going to be pretty simple:

  • Create two nodes, say, prev and current.
  • prev will initially point to null and the current will point to the head of the list.
  • Now, we have to traverse through the list till the current becomes null.
  • For every node, we are going to store the next of current in next and then will make the next of current point to prev. Finally we will make prev equal to current, and current equal to next.

By performing the above operations, we are changing the links of every node and ultimately reversing the list.

Algorithm

  • Create two nodes - prev and current.
  • The prev will initially point to null and current will point to head.
  • Traverse through the list till current becomes null.
  • Store the next of current in next.
  • Now, make next of current point to prev.
  • After pointing to previous, we will make the prev equal to the current, and current equal to the next.
  • In the end, after the full traversal, the prev will be our head.

Dry Run

Code Implementation




public class LinkedList {
  
    static Node head;
  
    static class Node {
  
        int data;
        Node next;
  
        Node(int d) {
            data = d;
            next = null;
        }
    }

    Node reverse(Node node) {
        Node prev = null;
        Node current = node;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        node = prev;
        return node;
    }

    void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
  
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(7);
        list.head.next.next = new Node(15);
        list.head.next.next.next = new Node(27);
          
        System.out.println("Given Linked list");
        list.printList(head);
        head = list.reverse(head);
        System.out.println("");
        System.out.println("Reversed linked list ");
        list.printList(head);
    }
}

Output

Original Linked list
1 7 15 27
Reversed linked list
27 15 7 1

Time Complexity : O(n), as list traversal is needed.
Space Complexity : O(1), as only temporary variables are being created.

Approach (Recursive)

The recursive approach is going to be very much similar to the iterative approach.

  • If the current node is the last, then we will mark it as our head, and it will now point to the prev node.
  • If the base case fails, we will store the next of current in temp, and make the current point to the previous node. After doing this, we will recur with next as current, and current as previous.

By performing the above operations, we are changing the links of every node and ultimately reversing the list.

Algorithm

  • Base case - If the current node is the last, make it the head and also make next of curr point to the prev.
  • Save the next of current in next1.
  • Now, make the next of the current point to the prev.
  • Recur with next1 as curr and curr as prev.

Finally, return the head.

Dry Run

Code Implementation


public class LinkedList {
  
    static Node head;
  
    static class Node {
  
        int data;
        Node next;
  
        Node(int d) {
            data = d;
            next = null;
        }
    }
    
    Node reverseUtil(Node curr, Node prev) {

        if (curr.next == null) {
            head = curr;

            curr.next = prev;
            return null;
        }

        Node next1 = curr.next;

        curr.next = prev;
  
        reverseUtil(next1, curr);
        return head;
    }

    void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
  
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(7);
        list.head.next.next = new Node(15);
        list.head.next.next.next = new Node(27);
        
  
        System.out.println("Original Linked list ");
        list.printList(head);
        Node res = list.reverseUtil(head, null);
        System.out.println("");
        System.out.println("");
        System.out.println("Reversed linked list ");
        list.printList(res);
    }
}

Output

Original Linked list
1 7 15 27
Reversed linked list
27 15 7 1

Time Complexity : O(n), as list traversal is needed.

So, in this article, we have tried to explain the most efficient approach to reverse a linked list in Java. Linked List reversal is an important concept when it comes to advanced concepts in the linked list. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.

Previous post LinkedList addAll() method in Java
Next post Python Program to Reverse a linked list

Leave a Reply

Your email address will not be published. Required fields are marked *