Rotate List
题目:
Given a list, rotate the list to the right by k places, where k is non-negative.
Example: Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.
分析:
这道题目有一个明显的陷阱,因为是right shift,所以k有可能大于数组的长度。于是乎遍历一次取得len,然后用k % len作为移动的位置。这里面有个特点,如果k % len == 0则可以return,因为相当于没有移动过。
解法:
class Solution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode *rotateRight(ListNode *head, int k) {
// write your code here
if (head == NULL || head->next == NULL) {
return head;
}
if (k == 0) {
return head;
}
// find length, in case k > len
int len = 0;
ListNode* curr = head;
while (curr != NULL) {
len++;
curr = curr->next;
}
k = k % len;
if (k == 0) {
return head;
}
// start to work on problem
ListNode* slow = head;
ListNode* fast = head;
for (int i = 0; i < k; i++) {
fast = fast->next;
}
while (fast->next != NULL) {
slow = slow->next;
fast = fast->next;
}
ListNode* newhead = slow->next;
slow->next = NULL;
fast->next = head;
return newhead;
}
};