Total Accepted: 55428 Total Submissions: 250727 Difficulty: Medium
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
.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getListLength(ListNode* head)
{
int len = ;
while(head){
len++;
head = head->next;
}
return len;
}
ListNode* rotateRight(ListNode* head, int k) {
int len = getListLength(head);
k = len == ? : len - k%len ;
if(head ==NULL || k== || k==len){
return head;
}
ListNode *newHead = NULL;
ListNode *cur = head;
int cnt = ;
while(cur){
++cnt;
if(cnt == k){
newHead = cur->next;
cur->next=NULL;
break;
}
cur = cur->next;
}
ListNode* p=newHead;
while(p && p->next){
p = p->next;
}
if(p){
p->next=head;
}
return newHead;
}
};