Friday, 27 September 2013

Rotating a Linked List C

Rotating a Linked List C

I am currently solving sum problems of list and function and i came across
this question i.e rotate a linked list by k anti clockwise. Here is the
code for same
void rotate_k(struct list *node,int k)
{
int count=0;
struct list *knode,*ptr=node;
while(ptr!=NULL && count < k)
{
ptr=ptr->next;
count++;
}
knode=ptr;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next =node;
node=knode->next;
knode->next=NULL;
}
Lets say if input is 1->2->3->4->5->6 and k=4.
The output should be 5->6->1->2->3->4 but the code gives the output
1->2->3->4->5 . Help needed :)

No comments:

Post a Comment