Answer to Question #234241 in C for SOM

Question #234241

Reverse a singly linked list using recursion.


1
Expert's answer
2021-09-07T23:22:17-0400


#include <iostream>


using namespace std;


struct Node {
    int d;
    struct Node* nt;
    Node(int d)
    {
        this->d = d;
        nt = NULL;
    }
};
  
struct LinkedList {
    Node* h;
    LinkedList()
    {
        h = NULL;
    }
  
    Node* reverse(Node* node)
    {
        if (node == NULL)
            return NULL;
        if (node->nt == NULL) {
            h = node;
            return node;
        }
        Node* node1 = reverse(node->nt);
        node1->nt = node;
        node->nt = NULL;
        return node;
    }
  
    void display()
    {
        struct Node* temp = h;
        while (temp != NULL) {
            cout << temp->d << " ";
            temp = temp->nt;
        }
    }
  
    void push(int d)
    {
        Node* temp = new Node(d);
        temp->nt = h;
        h = temp;
    }
};


int main()
{
    LinkedList a;
    a.push(10);
    a.push(20);
    a.push(30);
    a.push(40);
  
    cout << "Original linked list\n";
    a.display();
  
    a.reverse(a.h);
  
    cout << "\nReversed Linked list \n";
    a.display();
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS