Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

C++:
01 ListNode *rotateRight(ListNode *head, int k)
02 {
03         if(k==0)
04             return head;
05         if((head==NULL)||(head->next==NULL))
06             return head;
07         ListNode* test=head;
08         for(int i=0;i<k;i++){
09             if(test->next==NULL)
10                 test=head;
11             else
12                 test=test->next;
13         }
14         ListNode* tmp=head;
15         while(test->next!=NULL){
16             tmp=tmp->next;
17             test=test->next;
18         }
19         if(tmp->next==NULL)
20             return head;
21         ListNode* result=tmp->next;
22         tmp->next=NULL;
23         test->next=head;
24         return result;
25 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s