DATA STRUCTURES IN C – LINKED LIST (20 PROGRAMS)
Linked List in C- Reversing Every N Nodes of Linked List using Recursion :
Input: 1->2->3->4->5->6->7->8
Output: 3->2->1->6->5->4->8->7
Source Code :
#include<stdio.h> struct node { int data; struct node *next; }; struct node* reverse(struct node **head,int N) { struct node *next; struct node *prev=NULL; struct node *cur=*head; int i=1; struct node *holder=*head; while(cur!=NULL && i<=N) { next=cur->next; cur->next=prev; prev=cur; cur=next; i++; } if(next!=NULL) { holder->next = reverse(&next,N); } return prev; } void print(struct node **head) { struct node *temp=*head; printf("\nList:"); while(temp!=NULL) { printf("\n%d ",temp->data); temp=temp->next; } } int main() { struct node *one = (struct node*)malloc(sizeof(struct node)); struct node *two = (struct node*)malloc(sizeof(struct node)); struct node *three = (struct node*)malloc(sizeof(struct node)); struct node *four = (struct node*)malloc(sizeof(struct node)); struct node *five = (struct node*)malloc(sizeof(struct node)); struct node *six = (struct node*)malloc(sizeof(struct node)); struct node *seven = (struct node*)malloc(sizeof(struct node)); struct node *eight = (struct node*)malloc(sizeof(struct node)); struct node *head=one; one->data=1; one->next=two; two->data=2; two->next=three; three->data=3; three->next=four; four->data=4; four->next=five; five->data=5; five->next=six; six->data=6; six->next=seven; seven->data=7; seven->next=eight; eight->data=8; eight->next=NULL; printf("\nBefore Reversing:"); printf("\nLinked List:"); print(&head); head=reverse(&head,3); printf("\nAfter Reversing:"); printf("\nLinked List:"); print(&head); return 0; }
Output :
Before Reversing: Linked List: List: 1 2 3 4 5 6 7 8 After Reversing: Linked List: List: 3 2 1 6 5 4 8 7