Write a C program to reverse linked list using recursion. As we already know liked list data structure ,each node contains the data and address of next node. The last node contains data and NULL address.
For example if the linked list is 0->1->2->NULL then after reversing the given list it should be 2->1->0->NULL. In this recursion method instead of exchanging data part of the node we are going to exchange address part of the node.
c program to reverse linked list using recursion
#include<stdio.h> #include<malloc.h> typedef struct list_ { int id; struct list* next; } list; list* create_node() { list* node = (list*) malloc(sizeof(list)); return node; } void push_id_at_end(list **head, int id) { list *current = *head; // if the list is first node if (current == NULL) { current = create_node(); current->id = id; current->next = NULL; (*head) = current; return; } // go to last node while (current->next != NULL) current = current->next; list* new_node = create_node(); new_node->id = id; new_node->next = NULL; current->next = new_node; } void display_list_item(list *head) { if (head == NULL) return; while (head) { printf("%d ", head->id); head = head->next; } } list *head = NULL; void reverse_list(list* curr, list *prev) { if (curr) { reverse_list(curr->next, curr); curr->next = prev; } else { head = prev; } } int main() { //insert 0 ,1 and 2 int i; for (i = 0; i < 3; i++) { push_id_at_end(&head, i); } display_list_item(head); printf("\n"); reverse_list(head, NULL); display_list_item(head); printf("\n"); return 0; }
how it works :reverse linked list using recursion
void reverse_list(list* curr, list *prev) { if (curr) { reverse_list(curr->next, curr); curr->next = prev; } else { head = prev; } }
- Let see how we call this recursive function reverse_list(head, NULL);
- The reverse_list(..) function call itself by passing next node and its previous node, if the current node is not null.
- When the current node would be null during recursion , it will go into the else part of the program. when the current node would be null the previous node (prev) pointer point to last node. so by assigning head = prev, now head would be first node.
- After recursive function unwinds , in this case by curr->next = prev; we are assigning the address of previous node to the link part of current node.
The post c program to reverse linked list using recursion appeared first on wikistack.