In this program, we are going to share how to reverse a linked list using c programming language. If you are a beginner and want to start learning the c programming, then keep your close attention in this tutorial as I am going to share a c program to reverse a linked list.
Copy the below C program and execute it with the help of C compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
#include <stdio.h> #include <stdlib.h> #define MAX 100 struct leftnode { int num; struct leftnode *next; }; void linklist_add(struct leftnode **n, int val); void linklist_reverse(struct leftnode **n); void linklist_display(struct leftnode *n); int main(void) { struct leftnode *new = NULL; int i = 0; for(i = 0; i <= MAX; i++) linklist_add(&new, i); printf("Linked list before reversal:n"); linklist_display(new); linklist_reverse(&new); printf("Linked list after reversal:n"); linklist_display(new); return 0; } void linklist_add(struct leftnode **n, int val) { struct leftnode *temp = NULL; temp = malloc(sizeof(struct leftnode)); temp->num = val; temp->next = *n; *n = temp; } void linklist_reverse(struct leftnode **n) { struct leftnode *a = NULL; struct leftnode *b = NULL; struct leftnode *c = NULL; a = *n, b = NULL; while(a != NULL) { c = b, b = a, a = a->next; b->next = c; } *n = b; } void linklist_display(struct leftnode *n) { while(n != NULL) printf(" %d", n->num), n = n->next; printf("n"); } |
Liked this program? Do Like & share with your friends 🙂
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: c program to reverse a doubly linked list, recursive algorithm reverse linked list, recursive reverse doubly linked list in c, recursive reverse linked list, recursive reverse linked list c, recursive reverse singly linked list, reverse doubly linked list recursively, simple c program to reverse a linked list