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);
}
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;
}
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
}
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;
}
Top comments (0)