C++ program to print reverse a linked list without actually reversing
February 9, 2023
How to print reverse of a linked list without actually reversing in CPP programming?
In this article, we will learn to write a C++ program to print reverse of a linked list without actually reversing. For doing this we will create a function that will recursively print data from last node till the beginning node without actually reversing it. Further in this article we will see steps and algorithm for the same.
Steps write a C++ program to print reverse of a linked list without actually reversing
These steps are used to print reverse of a linked list without actually reversing in CPP programming
Start the program and initialize the variables.
Create function to create list (listBanao).
The above created function will help us to create linked list.
Now create another function toto print reverse of a linked list without actually reversing (reverse).
This function will have our main algorithm to reverse the given linked list.
This function will help to display the linked list in reverse order without actually reversing it.
#include<iostream>
using namespace std;
struct node
{
int num;
node *nextptr;
} *stnode; //node constructed
void listBanao (int n);
void reverse (node * stnode);
int main ()
{
int n, num, item;
cout << "Enter the number of nodes: ";
cin >> n;
listBanao (n);
cout << "After reversing\n";
reverse (stnode);
return 0;
}
void listBanao (int n) //function to create linked list.
{
struct node *frntNode, *tmp;
int num, i;
stnode = (struct node *) malloc (sizeof (struct node));
if (stnode == NULL)
{
cout << "Memory can not be allocated";
}
else
{
cout << "Enter the data for node 1: ";
cin >> num;
cout << "\n";
stnode->num = num;
stnode->nextptr = NULL; //Links the address field to NULL
tmp = stnode;
for (i = 2; i <= n; i++)
{
frntNode = (struct node *) malloc (sizeof (struct node));
if (frntNode == NULL) //If frntnode is null no memory cannot be allotted
{
cout << "Memory can not be allocated";
break;
}
else
{
cout << "Enter the data for node " << i << ": "; // Entering data in nodes.
cin >> num;
cout << "\n";
frntNode->num = num;
frntNode->nextptr = NULL;
tmp->nextptr = frntNode;
tmp = tmp->nextptr;
}
}
}
}
void reverse (node * stnode) //function to reverse linked list
{
if (stnode == NULL)
return;
reverse (stnode->nextptr);
cout << stnode->num << "\t";
}
Output
Enter the number of nodes: 5 Enter the data for node 1: 1 Enter the data for node 2: 2 Enter the data for node 3: 3 Enter the data for node 4: 4 Enter the data for node 5: 5 After reversing 5 4 3 2 1
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment