/* Explanation
write a program to given a linked list and input k
10->20->30->40->50->60->70->80->90->100
if k=2
output: 20->10->40->30->60->50->80->70->100->90
if k=3
output:30->20->10->60->50->40->90->80->70->100
if k=4
output:40->30->20->10->80->70->60->50->100->90
*/
/*Code*/
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int key;
struct node *next;
}NODE;
void print_link(NODE *p);
void reverse_link(NODE **root);
main()
{
NODE *root=NULL,*p,*q,*r,*s;
int key,i,iteration;
printf("Enter Numbers and -9999 to end\n");
do
{
scanf("%d",&key);
if(key == -9999)
{
break;
}
else
{
p= (NODE *)malloc(sizeof(NODE));
p->key = key;
p->next = NULL;
q = root;
if(q==NULL)
{
root = p;
}
else
{
while (q->next !=NULL)
{
q=q->next;
}
q->next = p;
}
}
}while(1);
printf("Enter K \n");
scanf("%d",&key);
printf("original\n");
print_link(root);
p = root;
iteration =1;
while(p!=NULL && key>=1)
{
q=p;
for(i=0;i<key-1 && p->next!=NULL;i++)
{
p=p->next;
}
if(iteration == 1)
{
root = p;
iteration++;
}
else
{
s->next = p;
}
r = p->next;
p->next = NULL;
s=q;
reverse_link(&q);
p=r;
}
s->next = p;
printf("reversed \n");
print_link(root);
}
void print_link(NODE *p)
{
while(p!=NULL)
{
printf("%d ",p->key);
p=p->next;
}
printf("\n");
return;
}
void reverse_link(NODE **root)
{
NODE *p,*q,*r=NULL;
if(*root == NULL)
return;
p=*root;
if(p->next != NULL)
{
q=p->next;
p->next = NULL;
while(q!=NULL)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
*root = p;
}
return;
}