Saturday, May 27, 2023

How to reverse a linked list in Java using Recursion and Iteration (Loop) - Example

Sure! Let's start with an example implementation of reversing a linked list in Java using recursion and iteration (loop). Let's assume we have a basic implementation of a linked list node as follows:


class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}



Now, let's see how we can reverse a linked list using recursion and iteration: 

Using Recursion:


class LinkedList {
    private ListNode head;

    // Recursive method to reverse a linked list
    private ListNode reverseRecursive(ListNode current, ListNode prev) {
        if (current == null) {
            return prev; // New head of the reversed list
        }
        
        ListNode next = current.next; // Store the next node
        
        // Reverse the link of the current node
        current.next = prev;
        
        return reverseRecursive(next, current); // Recursively move to the next node
    }

    // Method to initiate the reverse operation
    public void reverse() {
        head = reverseRecursive(head, null);
    }
}



Using Iteration (Loop):


class LinkedList {
    private ListNode head;

    // Method to reverse a linked list using iteration
    public void reverse() {
        ListNode prev = null;
        ListNode current = head;
        
        while (current != null) {
            ListNode next = current.next; // Store the next node
            current.next = prev; // Reverse the link of the current node
            prev = current; // Move prev and current one step forward
            current = next;
        }
        
        head = prev; // Update the head of the reversed list
    }
}

To test the implementation, you can create a linked list, add some nodes, and then call the reverse() method. Here's an example:


public class Main {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        
        // Add nodes to the linked list
        linkedList.head = new ListNode(1);
        linkedList.head.next = new ListNode(2);
        linkedList.head.next.next = new ListNode(3);
        linkedList.head.next.next.next = new ListNode(4);
        linkedList.head.next.next.next.next = new ListNode(5);
        
        // Print the original linked list
        System.out.println("Original Linked List:");
        linkedList.printLinkedList();
        
        // Reverse the linked list
        linkedList.reverse();
        
        // Print the reversed linked list
        System.out.println("Reversed Linked List:");
        linkedList.printLinkedList();
    }
}

This is a basic example of how you can reverse a linked list using recursion and iteration in Java. Remember to adjust the implementation according to your specific requirements and the structure of your linked list.

No comments:

Post a Comment