题目分析:
将一个链表向右旋转k
位。如1 -> 2 -> 3 -> 4
向右旋转3位则为 2 -> 3 -> 4 -> 1
。
解题思路
求出链表的长度len, 则我们需要移k%len位。找到需要断开的位置重接一下即可。例子如上。
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
ListNode *p = head, *q;
int len = 1;
while(p->next) {
len++;
p = p->next;
}
if(!(k %= len)) return head;//if k%len == 0, needn't do anything
k = len-k;
p->next = head;//let the last node point to head
while(k--)
p = p->next;//find the kth node
head = p->next;
p->next = NULL;//break the list
return head;
}
};