Question
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
Solution
-
典型的fast-slow指针问题。
-
有很多小细节,k指向最后一个节点,k指向第一个节点,k大于所有节点的个数,链表中节点个数为1,k为0,都要考虑进去。
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL || k == 0)
return head;
int count = 0;
ListNode* tmp = head;
while (tmp != NULL) {
tmp = tmp->next;
count++;
}
if (k > count) {
if (k % count == 0)
return head;
k = k % count;
}
ListNode* slow = head;
ListNode* fast = head;
int i;
for (i = 0; i < k - 1; i++) {
if (fast != NULL) {
fast = fast->next;
} else
return head;
}
ListNode* pre = NULL;
while (fast != NULL && fast->next != NULL) {
pre = slow;
slow = slow->next;
fast = fast->next;
}
if (pre == NULL)
return head;
else
pre->next = NULL;
if (fast != NULL)
fast->next = head;
head = slow;
return head;
}
};