C++ Program For Printing Reverse Of A Linked List Without Actually Reversing
Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.
Note that the question is only about printing the reverse. To reverse the list itself see this
Difficulty Level: Rookie
Algorithm:
printReverse(head)
1. call print reverse for head->next
2. print head->data
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
int data;
Node* next;
};
void printReverse(Node* head)
{
if (head == NULL)
return ;
printReverse(head->next);
cout << head->data << " " ;
}
void push(Node** head_ref,
char new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main()
{
Node* head = NULL;
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printReverse(head);
return 0;
}
|
Output:
4 3 2 1
Time Complexity: O(n)
Space Complexity: O(n) for call stack since using recursion
Please refer complete article on Print reverse of a Linked List without actually reversing for more details!
Last Updated :
08 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...