Site icon Study Algorithms

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

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;
};

void printListFromEnd(struct node * listHead)
{
	// terminating condition for the recursive loop
	if(listHead == NULL)
	{
		return;
	}

	// the recursive call, this calls the next node
	printListFromEnd(listHead -> next);

	// this statement will be executed for the first time
	// when we reach the last node
	printf("%d ",head -> data);
}

//helper function
struct node * addElement(struct node *head, int number)
{
	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;
	return head;
}

int main(void)
{
	//creating a list
	struct node * listHead = (struct node*)malloc(sizeof(struct node));
	listHead->data = 4;
	listHead->next = NULL;
	listHead = addElement(listHead, 8);
	listHead = addElement(listHead, 15);
	listHead = addElement(listHead, 16);
	listHead = addElement(listHead, 23);
	listHead = addElement(listHead, 42);

	printListFromEnd(listHead);  // Printing the list.

	return 0;
}
Exit mobile version