- Write a C program to read a linked list in reverse direction using recursion.
To print a singly linked list in reverse order, we will use a recursive function.
We will store the head node of linked list in function stack and then recursively call reverseLLPrint function for sub linked list starting from head->next. When sub linked list get printed in reverse order then we will print the head node stored in function stack.
Input Linked List 1 --> 8 --> 3 --> 20 --> 5 --> NULL Nodes in reverse order 5 20 3 8 1Singly linked list's node structure is as follows:
struct node {
int data;
struct node *next;
}
Function void reverseLLPrint(struct node *head) is a recursive function which takes head pointer of a linked list prints it's nodes in reverse order.
void reverseLLPrint(struct node *head) {
if (head != NULL) {
reverseLLPrint(head->next);
printf("%d ", head->data);
}
}
C program to print a linked list in reverse using recursion
#include <stdio.h>
#include <stdlib.h>
/* A structure of linked list node */
struct node {
int data;
struct node *next;
} *head;
void initialize(){
head = NULL;
}
/*
Given a Inserts a node in front of a singly linked list.
*/
void insert(int num) {
/* Create a new Linked List node */
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = num;
/* Next pointer of new node will point to head node of linked list */
newNode->next = head;
/* make new node as new head of linked list */
head = newNode;
printf("Inserted Element : %d\n", num);
}
/*
Prints Linked List in reverse order without reversing it.
*/
void reverseLLPrint(struct node *head) {
if (head != NULL) {
reverseLLPrint(head->next);
printf("%d ", head->data);
}
}
/*
Prints a linked list from head node till tail node
*/
void printLinkedList(struct node *nodePtr) {
while (nodePtr != NULL) {
printf("%d", nodePtr->data);
nodePtr = nodePtr->next;
if(nodePtr != NULL)
printf("-->");
else
printf("-->NULL");
}
}
int main() {
initialize();
/* Creating a linked List*/
insert(8);
insert(3);
insert(2);
insert(7);
insert(9);
printf("\nLinked List\n");
printLinkedList(head);
printf("\nPrinting Linked List in Reversed Order\n");
reverseLLPrint(head);
return 0;
}
OutputInserted Element : 8 Inserted Element : 3 Inserted Element : 2 Inserted Element : 7 Inserted Element : 9 Linked List 9-->7-->2-->3-->8-->NULL Printing Linked List in Reversed Order 8 3 2 7 9