//A program for reversing each k-nodes of blocks in the program.....Tested and working
input:- 1 2 3 4 5 6 7 8 9 10 11
for k=3
output:- 3 2 1 6 5 4 9 8 7 10 11
#include<stdio.h>
#include<stdlib.h>
typedef struct Linkedlist
{
int data;
struct Linkedlist *next;
} List;
void InsertNode(List **Head,int data)
{
List *temp,*ptr;
temp=(List*)malloc(sizeof(List));
temp->data=data;
temp->next=NULL;
if(!*Head)
{
*Head=temp;
return ;
}
ptr=*Head;
while(ptr->next)
ptr=ptr->next;
ptr->next=temp;
}
void Traverse(List *Head)
{
if(!Head)return;
printf("%d ",Head->data);
Traverse(Head->next);
}
void Kreverse(List **Head,int k)
{
List *prev,*First,*Last,*ptr,*temp;int i=1;
First=ptr=*Head;
i=k-1;
if(k==1||!*Head)return ;
while(1)
{
while(ptr->next&&i)
{
ptr=ptr->next;
i--;
}
if(i)
return;
if(*Head==First)
*Head=ptr;
else
{
First->next=ptr;
First=Last;
}
prev=Last=ptr->next;
ptr=First;
i=k-1;
while(i)
{
temp=ptr;
ptr=ptr->next;
temp->next=prev;
prev=temp;
i--;
}
ptr->next=prev;
ptr=Last;
if(!ptr)return;
i=k-1;
}
}
int main(void)
{
List *Head=NULL;
int i=0,data,n;
printf("Enter the no. of input you want to enter\n");
scanf("%d",&n);
printf("\nEnter the data\n");
while(i<n)
{
scanf("%d",&data);
InsertNode(&Head,data);
i++;
fflush(stdin);
}
printf("List is\n");
Traverse(Head);
printf("\nEnter the value for k reverse\n");
int k;
scanf("%d",&k);
printf("\nReversed list is\n");
Kreverse(&Head,k);
Traverse(Head);
return 0;
}
input:- 1 2 3 4 5 6 7 8 9 10 11
for k=3
output:- 3 2 1 6 5 4 9 8 7 10 11
#include<stdio.h>
#include<stdlib.h>
typedef struct Linkedlist
{
int data;
struct Linkedlist *next;
} List;
void InsertNode(List **Head,int data)
{
List *temp,*ptr;
temp=(List*)malloc(sizeof(List));
temp->data=data;
temp->next=NULL;
if(!*Head)
{
*Head=temp;
return ;
}
ptr=*Head;
while(ptr->next)
ptr=ptr->next;
ptr->next=temp;
}
void Traverse(List *Head)
{
if(!Head)return;
printf("%d ",Head->data);
Traverse(Head->next);
}
void Kreverse(List **Head,int k)
{
List *prev,*First,*Last,*ptr,*temp;int i=1;
First=ptr=*Head;
i=k-1;
if(k==1||!*Head)return ;
while(1)
{
while(ptr->next&&i)
{
ptr=ptr->next;
i--;
}
if(i)
return;
if(*Head==First)
*Head=ptr;
else
{
First->next=ptr;
First=Last;
}
prev=Last=ptr->next;
ptr=First;
i=k-1;
while(i)
{
temp=ptr;
ptr=ptr->next;
temp->next=prev;
prev=temp;
i--;
}
ptr->next=prev;
ptr=Last;
if(!ptr)return;
i=k-1;
}
}
int main(void)
{
List *Head=NULL;
int i=0,data,n;
printf("Enter the no. of input you want to enter\n");
scanf("%d",&n);
printf("\nEnter the data\n");
while(i<n)
{
scanf("%d",&data);
InsertNode(&Head,data);
i++;
fflush(stdin);
}
printf("List is\n");
Traverse(Head);
printf("\nEnter the value for k reverse\n");
int k;
scanf("%d",&k);
printf("\nReversed list is\n");
Kreverse(&Head,k);
Traverse(Head);
return 0;
}
No comments:
Post a Comment