Open In App

Reverse a linked list using recursion

Last Updated : 12 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list, the task is to reverse the linked list by changing the links between nodes.

Examples: 

Input: Linked List = 1 -> 2 -> 3 -> 4 -> NULL 
Output: 4 -> 3 -> 2 -> 1 -> NULL

Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL 
Output: 5 -> 4 -> 3 -> 2 -> 1 -> NULL

Approach:

To reverse a linked list using recursion, we start at the head of the list and recursively call the function on the next node until we reach the end. Once we reach the last node, that node becomes the new head of the reversed list.

Assume, we are currently at a node (let’s call it node x), also we already have head of reversed portion of the linked list that comes after node x. To connect node x to this reversed part, we just need to append this x at the last node of already reverse list. After doing this, we have to return the head of reversed list again.

Working:

Code Implementation:

C++
// Recursive C++ program to reverse a linked list
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Function to reverse the linked list
Node* reverseList(Node* head) {
    if (head == nullptr || head->next == nullptr)
        return head;

    // Reverse the rest of the list
    Node* revHead = reverseList(head->next);
    
    // Make the current head the last node
    head->next->next = head;
    
    // Update the next of current head to NULL
    head->next = nullptr;
    
    // Return the new head of the reversed list
    return revHead;
}

void printList(Node* head) {
  	Node* curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {

    // Create a hard-coded linked list:
    // 1 -> 2 -> 3 -> 4 -> 5
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);

    head = reverseList(head);
    printList(head);

    return 0;
}
C
// Recursive C program to reverse a linked list
#include <stdio.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to reverse the linked list
struct Node* reverseList(struct Node* head) {
    if (head == NULL || head->next == NULL)
        return head;

    // Reverse the rest of the list
    struct Node* revHead = 
                      reverseList(head->next);
    
    // Make the current head the last node
    head->next->next = head;
    
    // Update the next of current head to NULL
    head->next = NULL;
    
    // Return the new head of the reversed list
    return revHead;
}


void printList(struct Node *head) {
    struct Node *curr = head;
    while (curr != NULL){
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
}

struct Node* createNode(int x) {
    struct Node* newNode = 
       (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->next = NULL;
    return newNode;
}

int main() {
  
    // Create a hard-coded linked list:
    // 1 -> 2 -> 3 -> 4 -> 5
    struct Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);

    head = reverseList(head);
    printList(head);

    return 0;
}
Java
// Recursive Java program to reverse a linked list
class Node {
    int data;
    Node next;
    Node(int x){
        data = x;
        next = null;
    }
}

class GfG {

    // Function to reverse the linked list
    static Node reverseList(Node head){
        if (head == null || head.next == null)
            return head;

        // Reverse the rest of the list
        Node revHead = reverseList(head.next);

        // Make the current head the last node
        head.next.next = head;

        // Update the next of current head to NULL
        head.next = null;

        // Return the new head of the reversed list
        return revHead;
    }

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

    public static void main(String[] args){

        // Create a hard-coded linked list:
        // 1 -> 2 -> 3 -> 4 -> 5
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);

        head = reverseList(head);
        printList(head);
    }
}
Python
# Recursive Python program to reverse
# a linked list
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to reverse the linked list
def reverse_list(head):
    if head is None or head.next is None:
        return head

    # Reverse the rest of the list
    revHead = reverse_list(head.next)
    
    # Make the current head the last node
    head.next.next = head
    
    # Update the next of current head to None
    head.next = None
    
    # Return the new head of the reversed list
    return revHead

def print_list(head):
    curr = head
    while curr:
        print(curr.data, end=" ")
        curr = curr.next
    print()

if __name__ == "__main__":

    # Create a hard-coded linked list:
    # 1 -> 2 -> 3 -> 4 -> 5
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)

    head = reverse_list(head)   
    print_list(head)
C#
// Recursive C# program to reverse a linked list
using System;

class Node {
    public int data;
    public Node next;
    public Node(int x){
        data = x;
        next = null;
    }
}

class GfG {
  
    // Function to reverse the linked list
    static Node ReverseList(Node head){
        if (head == null || head.next == null)
            return head;

        // Reverse the rest of the list
        Node revHead = ReverseList(head.next);

        // Make the current head the last node
        head.next.next = head;

        // Update the next of current head to null
        head.next = null;

        // Return the new head of the reversed list
        return revHead;
    }

    static void PrintList(Node head){
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main(){

        // Create a hard-coded linked list:
        // 1 -> 2 -> 3 -> 4 -> 5
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);

        head = ReverseList(head);
        PrintList(head);
    }
}
JavaScript
// Recursive javascript program to reverse
// a linked list
class Node {
    constructor(x){
        this.data = x;
        this.next = null;
    }
}

// Function to reverse the linked list
function reverseList(head)
{
    if (head === null || head.next === null)
        return head;

    // Reverse the rest of the list
    const revHead = reverseList(head.next);

    // Make the current head the last node
    head.next.next = head;

    // Update the next of current head to null
    head.next = null;

    // Return the new head of the reversed list
    return revHead;
}

function printList(head)
{
    let curr = head;
    while (curr !== null) {
        console.log(curr.data);
        curr = curr.next;
    }
}

// Create a hard-coded linked list:
// 1 -> 2 -> 3 -> 4 -> 5
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

head = reverseList(head);
printList(head);

Output
 5 4 3 2 1

Time Complexity: O(n), since we are visiting each node only once.
Auxiliary Space: O(n) , Recursion call stack space.

Related Article:



Next Article
Article Tags :
Practice Tags :

Similar Reads