Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a Linked List C

Tags:

c

linked-list

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 :)

like image 571
user2714823 Avatar asked Dec 02 '25 21:12

user2714823


2 Answers

You are not modifying the original list (node parameter)

struct list *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;

   return knode; //<-- THIS IS THE NEW LIST
}

Also, knode->next=NULL is strange; you should do at the node that is (was) previous to knode (this is what is deleting the 6 from your results).

like image 145
SJuan76 Avatar answered Dec 05 '25 11:12

SJuan76


SJuan's method is correct but if you want to do it your way without using a return value, then you need to use a double pointer for node. Remember, C makes copies of variables you pass into a function. If the original root node was a pointer (which I'm assuming it was) than you need to make a pointer to a pointer otherwise you are just making changes to a copy of the root node pointer, not the actual root node pointer.

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;
}
like image 29
Nate Avatar answered Dec 05 '25 11:12

Nate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!