Recursively reversing a Linked List – A simple implementation

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 linked list, using recursion.

Problem Statement Understanding

Let the given linked list be 1 -> 2 -> 3 -> 4. Now, with the help of recursion, we have to reverse the linked list. The reverse linked list is 4 -> 3 -> 2 -> 1.

Input:

Output:

Explanation: The given linked list has been reversed.

This question is not a very complex one. We just have to reverse the given linked list. The only requirement is to use recursion.

We should not think that recursion is tough. We will be doing almost the same operations that we would’ve done with a loop. The only addition will be that we will keep recurring until we hit the base case. Let us have a glance at the approach.

Approach

The approach is going to be pretty simple. We are going to traverse through the list and make the previous node of the current node as its next node. After this, we are going to recur for the next node.

When we reach the last node, we will make it the head of our new linked list, and then recursively the other nodes will get added to our new linked list one by one.

Algorithm

  • Base Case - If the node is NULL, return NULL.
  • Another Base Case - If node - > next is NULL, we will make the node the head of the new linked list, as it is the last node of the list.
  • If the base cases fail, proceed further.
  • Create a new node node1 and store the recurred value of node -> next in it.
  • Now, as the recursive calls return values, make node1 -> next point to the current node.
  • Make current node - > next point to NULL
  • By doing the above steps, we are changing the links of every node, i.e. we are making the current node point to its previous node.
  • In the end, return current node.

Dry Run

Code Implementation


#include 
using namespace std;

struct Node {
    int data;
    struct Node* next;
    Node(int data)
    {
        this->data = data;
        next = NULL;
    }
};
  
struct LinkedList {
    Node* head;
    LinkedList()
    {
        head = NULL;
    }
  
    // Function to reverse the list
    Node* reverse(Node* node)
    {
        if (node == NULL)
            return NULL;

        // if current node is the last node
        if (node->next == NULL) {
            head = node;
            return node;
        }
        // recur for the next node
        Node* node1 = reverse(node->next);

        // Change the links accordingly
        node1->next = node;
        node->next = NULL;
        return node;
    }

    void print()
    {
        struct Node* temp = head;
        while (temp != NULL) {
            cout << temp->data << " ";
            temp = temp->next;
        }
    }
  
    void push(int data)
    {
        Node* temp = new Node(data);
        temp->next = head;
        head = temp;
    }
};
  
int main()
{
    LinkedList ll;
    ll.push(4);
    ll.push(3);
    ll.push(2);
    ll.push(1);
    cout << "Given linked list\n";
    ll.print();
    ll.reverse(ll.head);
    cout << "\nReversed Linked list \n";
    ll.print();
    return 0;
}

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class ReverseLinkedListRecursive {
    

    static class Node {
        public int data;
        public Node next;

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

    static class LinkedList {
        public Node head;

        public LinkedList() {
            this.head = null;
        }

        public void insertNode(int nodeData) {
            Node node = new Node(nodeData);

            if (this.head != null) {
                node.next = head;
            }
            this.head = node;
        }
    }


    public static void printSinglyLinkedList(Node node,
                        String sep) throws IOException {
        while (node != null) {
            System.out.print(String.valueOf(node.data) + sep);
            node = node.next;
        }
    }


    static Node reverse(Node head) {
        if(head == null) {
            return head;
        }


        if(head.next == null) {
            return head;
        }

        Node newHeadNode = reverse(head.next);


        head.next.next = head;
        head.next = null;

        return newHeadNode;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
            LinkedList llist = new LinkedList();
            llist.insertNode(4);
            llist.insertNode(3);
            llist.insertNode(2);
            llist.insertNode(1);
            System.out.println("Given linked list:");
            printSinglyLinkedList(llist.head, " ");
            System.out.println();
            System.out.println("Reversed Linked list:");
            Node llist1 = reverse(llist.head);
            printSinglyLinkedList(llist1, " ");

        scanner.close();
    }
}

Output

Given linked list
1 2 3 4
Reversed Linked list
4 3 2 1

Space Complexity: O(n), space required for recursion stack.

So, in this article, we have tried to explain the most efficient approach to recursively reverse a linked list. This is an important question when it comes to coding interviews. 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 Priority Queue using a Linked List
Next post Insertion Sort for Doubly Linked List

Leave a Reply

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