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
.
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int count=0;
ListNode* curr=head,*curr1=head;
while(curr!=NULL){
curr=curr->next;
++count;
}
curr=head;
if(count==0||k%count==0)
return head;
k%=count;
for(int i=0;i<k;++i){
curr=curr->next;
}
while(curr->next!=NULL){
curr=curr->next;
curr1=curr1->next;
}
curr->next=head;
head=curr1->next;
curr1->next=NULL;
return head;
}
};