Home Linked List How will you print a Linked List in a reversed order.

# How will you print a Linked List in a reversed order.

0 comment

Question: Print the Linked List in reverse order. The actual structure of the Linked List must remain intact.

Input: 4, 8, 15, 16, 23, 42

Output: 42, 23, 16, 15, 8, 4

We just discussed how to reverse a Linked List in an older post.

But, in the above described method we changed the entire structure of the Linked List, the last node was no longer the last node and the head node had also changed.
We might encounter cases, where we just need to print the Linked list in reverse order. This can be easily achieved via recursion. We will use the most basic concept of recursion, which is that the function will always return to its calling point.
We will travel to the end of the list recursively, and when we reach NULL, we will call back each of the iteration, printing the value at the node.

Here is a implementation of the same.

#include<stdio.h>

struct node
{
int data;
struct node * next;
};

{
// terminating condition for the recursive loop
{
return;
}

// the recursive call, this calls the next node

// this statement will be executed for the first time
// when we reach the last node
}

//helper function
{
struct node * temp = (struct node*)malloc(sizeof(struct node));
temp -> data = number;
temp -> next = NULL;
struct node * temp2 = head;
while(temp2 -> next != NULL)
temp2 = temp2 -> next;
temp2 -> next = temp;
}

int main(void)
{
//creating a list
struct node * listHead = (struct node*)malloc(sizeof(struct node));
}