The task is to print the reverse of a given linked list by using recursive function. The program must print the reverse but not reverse the list that means the order of the nodes remains the same
Here, the program will move head pointer containing the address of a first node to next node until the NULL is examined which is stored in last node of a list and printing the data of a head node.
Example
Input: 29 34 43 56 Output: 56 43 34 29
Firstly, the nodes are inserted into the list and a pointer will start pointing to the nodes that are inserted. After final list is created let’s say temp pointer will be initialised with the first node pointer and it keeps incrementing till the node’s next address is NULL as the last node points to nothing and from the last node the list is traversed till the head pointer. It will display the reverse of a list without actually reversing a list.
The below code shows the c implementation of the algorithm given.
Algorithm
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *next Step 2 ->Declare function void reverse(node* head) IF head == NULL return Call reverse(head->next) Print head->data Step 3 -> Declare Function void push(node** header, char newdata) Allocate memory using malloc Set newnode->data = newdata Set newnode->next = (*header) Set (*header) = newnode Step 4 ->In Main() Create list using node* head = NULL Insert elements through push(&head, 56) Call reverse(head) STOP
Example
#include<stdio.h> #include<stdlib.h> //creating structure for a node struct node { int data; node* next; }; //function to print reverse of the data in the list void reverse(node* head) { if (head == NULL) return; reverse(head->next); printf("%d ", head->data); } //function to puch the node in the list void push(node** header, char newdata) { struct node* newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = newdata; newnode->next = (*header); (*header) = newnode; } int main() { node* head = NULL; push(&head, 56); //calling function to push 56 in the list push(&head, 43); push(&head, 34); push(&head, 29); reverse(head); return 0; }
Output
If we run above program then it will generate following output.
reverse of a linked list 56 43 34 29