问题:
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
.
注意,当找到split point之后,两段子链表内的相对顺序是不变的。所以我的思路是,先把把链表连成一个环,然后找到相应的split point, 断开即可。
代码:
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (k == 0) return head;
if (!head) return NULL;
if (!head->next) return head;
ListNode *tail = head;
int len = 1;
while (tail->next) {
len ++;
tail = tail->next;
}
tail->next = head;
k = k % len;
for (int i = 1; i < len - k; i ++) {
head = head->next;
}
ListNode *newHead = head->next;
head->next = NULL;
return newHead;
}
};