Created
September 16, 2012 09:53
-
-
Save sahilalipuria/3731831 to your computer and use it in GitHub Desktop.
Rotate a Linked List Counter Clockwise by k nodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<conio.h> | |
#include<stdlib.h> | |
struct node{ | |
int data; | |
node *link; | |
}*start=NULL,*p,*q,*r,*temp; | |
void insert(int val) | |
{ | |
node *temp=(struct node*)malloc(sizeof(struct node)); | |
temp->data=val; | |
if(start==NULL) | |
{ | |
temp->link=NULL; | |
start=temp; | |
} | |
else | |
{ | |
p=start; | |
while(p->link!=NULL) | |
p=p->link; | |
p->link=temp; | |
temp->link=NULL; | |
} | |
} | |
void rotate(int k) | |
{ | |
p=r=start; | |
if(k>=3) | |
for(int i=1;i<k-1;i++) | |
p=p->link; | |
r=p->link; | |
while(r->link!=NULL) | |
r=r->link; | |
r->link=start; | |
start=p->link; | |
p->link=NULL; | |
} | |
void display() | |
{ | |
p=start; | |
printf(“%d”,p->data); | |
while(p->link!=NULL) | |
{ | |
p=p->link; | |
printf(“–>%d”,p->data); | |
} | |
printf(“\n”); | |
} | |
int main() | |
{ | |
insert(1); | |
insert(2); | |
insert(3); | |
insert(4); | |
display(); | |
rotate(3); | |
display(); | |
getch(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment