Printing Linked List in Reverse Order without actually Reversing it

Printing Linked List in Reverse Order without actually Reversing it” is again one of the famous problems of the Linked List. Here, we are given a linked list and our task is to print the given linked list in reverse order without actually reversing it.

We can use recursion to solve the following problem.

Example:

Suppose, we need to print the given linked list in reverse order without actually reversing it, then:
LINKED LIST:       12 -> 13 -> 14 -> 15 -> 16
Output List:       16 -> 15 -> 14 -> 13 -> 12

C++ Program to print linked list in reverse order:

/* C++ Program to Reverse a Linked List without actually reversing it */
#include<bits/stdc++.h>
using namespace std;

/* strcuture of the Node of the Linked List */
typedef struct node
{
    int data;
    struct node *next;
}Node;

/* Function to insert node at the end of the linked list */
void insert_end(Node **head, int ele)
{
    /* Creating a new node */
    Node *new_node;
    new_node = (struct node*)malloc(sizeof(struct node));
    new_node->data = ele;
    new_node->next = NULL;
    
    /* check whether the linked list is empty or not */
    
    /* If Linked List is empty, new node will become head of the linked list */
    if(*head == NULL)     
    {
        *head = new_node;
        return;
    }
    
    /* If Linked List is not empty, then traverse the complete linked list and last node
    of the linked list will points to the new node of the linked list */
    Node *temp = NULL;
    temp = (*head);
    while(temp->next != NULL)
    temp=temp->next;
    temp->next = new_node;
}

/* Function to print the Linked List */
void print_actual(Node *head)
{
    Node *temp = head;
    while(temp != NULL)
    {
        cout << temp -> data << " ";
        temp = temp -> next;
    }
    cout<<endl;
}

/* Function to print the linked list in reverse order*/
void print_reverse(Node *head)
{
    if(head==NULL)
    return;
    print_reverse(head->next);
    cout<<head->data<<" ";
}

int main()
{
    Node *head = NULL;
    /* Insert Some Nodes in the Linked List */
    insert_end(&head,12);
    insert_end(&head,13);
    insert_end(&head,14);
    insert_end(&head,15);
    insert_end(&head,18);
    cout<<"Actual Linked List Elements:\n";
    print_actual(head);
    cout<<"\nPrinting Reverse Order of the Linked List:\n";
    print_reverse(head);
}
OUTPUT:
Actual Linked List Elements:
12 13 14 15 18 
 
Printing Reverse Order of the Linked List:
18 15 14 13 12

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *