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
.
——————————————————————————————————————————————————————————————————
基本思路:
一开始错误把题目理解为了左移。
其实左移和右移可以等价起来,即右移 k 个元素 等价 左移 len-k 个元素。(len是list的长度)
几个细节:
1. k>=len时, k = k % len. (0<=k<=len-1)
2. 取模后,k = len-k. (1<=k<=len) 如果 k==len,直接返回head。
处理一般情况:
根据k的大小,将 list 分为长度 len-k 和 k 2个部分,分别记为 L1 和 L2。
然后将 L1 的最后一个节点的 next 设置为 NULL;将 L2 的最后一个节点的 next 设置为原 list 的 head。
最后将L2 的头节点作为旋转后的 list 新头节点返回即可。
ListNode *rotateRight(ListNode *head, int k) {
if(NULL==head || NULL==head->next || k<=0){
return head;
}
int len = 0;
ListNode* cur = head;
ListNode* tail;
while(cur!=NULL){
len = len + 1;
if(cur->next == NULL){
tail = cur;
}
cur = cur->next;
}
k = k%len;
k = len -k;
if(k==len){
return head;
}
ListNode* MiddleNode = head;
while(k>1){
MiddleNode = MiddleNode->next;
k = k-1;
}
ListNode* NewHead = MiddleNode->next;
MiddleNode->next = NULL;
tail->next = head;
return NewHead;
}