In this program, we are going to share a C program to reverse a linked list in groups of given size. 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 in groups of given size with the output.
We have designed this program for beginners for learning purpose. Copy below c program and execute it with c compiler to see the output of the 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 65 66 67 68 69 70 71 72 73 74 75 |
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node* next; }; struct Node *reverse (struct Node *head, int k) { struct Node* current = head; struct Node* next = NULL; struct Node* prev = NULL; int count = 0; while (current != NULL && count < k) { next = current->next; current->next = prev; prev = current; current = next; count++; } if (next != NULL) head->next = reverse(next, k); return prev; } void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } void printList(struct Node *node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } } int main(void) { struct Node* head = NULL; push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf("\nGiven linked list \n"); printList(head); head = reverse(head, 3); printf("\nReversed Linked list \n"); printList(head); return(0); } |
Given Linked List
1 2 3 4 5 6 7 8 9
Reversed list
3 2 1 6 5 4 9 8 7
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.