DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

Reverse Linked List

We use Recursion to reverse singly linked list .

We can print 1 to 5 using recursion . Just making one line down we could print 5 to 1 .

Example -

void rec(int i, int n)
{
    // base case
    if (i == n)
        return;
cout << i << endl;

    rec(i + 1, n);

}
int main()
{
    int n = 5;
    rec(1, n);
}
Enter fullscreen mode Exit fullscreen mode

Output - 1
2
3
4
5
If we just make down one line it will be reversed

void rec(int i, int n)
{
    // base case
    if (i == n)
        return;


    rec(i + 1, n);
    cout << i << endl;

}

Enter fullscreen mode Exit fullscreen mode

So , Let's convert it to Linked List .....

In Linked List , For traversing we take tmp Node . We don't use head Node here . Ok?
Then what will be the base case ?
Guess.....

Think.....

Done?

if(tmp == NULL) {
return ;
}

Then how to call rec function ?

See the recursion function in the upper ?

What to write ?

Yeah , You guessed right

rec(tmp->next) ;
cout << tmp->val << endl ;

This is how we easily reversed linked list ....

include

using namespace std;

struct Node {
int val;
Node* next;
Node(int x) : val(x), next(NULL) {}
};

void reversePrint(Node* tmp) {
if (tmp == NULL) return;

reversePrint(tmp->next); // Recursive call
cout << tmp->val << " "; // Print after recursion
Enter fullscreen mode Exit fullscreen mode

}

int main() {
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);

reversePrint(head);
return 0;
Enter fullscreen mode Exit fullscreen mode

}

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay