Search⌘ K

Print a Reversed Linked List

Explore how to print a linked list in reverse without modifying its content by applying recursive techniques. Understand the role of base and recursive cases, and see how the recursion stack facilitates reverse traversal. This lesson helps you implement and grasp recursive logic on linked lists for interview-ready coding skills.

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:

C++
#include<iostream>
using namespace std;
// Node Class
class Node
{
public:
int data;
Node *next;
};
//prints a linked list in reverse manner
void reverse(Node* head)
{ //base case
if(head == NULL)
return;
//recursive case
reverse(head->next);
cout << head->data << " ";
}
//push a new node
void insertAtHead(Node** head, int new_data)
{
//make a new node
Node* new_node = new Node();
//insert data in the node
new_node->data = new_data;
//make the new_node->next points to head
new_node->next = (*head);
//head points at new node
(*head) = new_node;
}
//Driver Function
int main()
{
//emty list
Node* head = NULL;
//insert Data in the list
insertAtHead(&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;
}
...