Print a Reversed Linked List
This lesson helps you print the linked list in reversed manner using recursion.
Print Reversed Linked List
Given a linked list, we do not have to change the content of the list, but we have to access each node in such a way that the linked list is printed in a reversed manner.
The following illustration explains the concept:
Implementing the Code
The following code helps to print the linked list in a reversed manner using recursion:
Press + to interact
#include<iostream>using namespace std;// Node Classclass Node{public:int data;Node *next;};//prints a linked list in reverse mannervoid reverse(Node* head){ //base caseif(head == NULL)return;//recursive casereverse(head->next);cout << head->data << " ";}//push a new nodevoid insertAtHead(Node** head, int new_data){//make a new nodeNode* new_node = new Node();//insert data in the nodenew_node->data = new_data;//make the new_node->next points to headnew_node->next = (*head);//head points at new node(*head) = new_node;}//Driver Functionint main(){//emty listNode* head = NULL;//insert Data in the listinsertAtHead(&head, 5);insertAtHead(&head, 4);insertAtHead(&head, 3);insertAtHead(&head, 2);insertAtHead(&head, 1);cout<<"List 1->2->3->4->5 \n Reverse List:";reverse(head);return 0;}
...