题目:
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
.
分析:
代码:
/**
* 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 (k<1 || head == NULL)return head;
int pos = 0, total;
bool sign = false;
ListNode *r = new ListNode(0), *slow, *fast = head, *pre = r, *end = NULL;
r->next = head;
while (fast&&fast->next) {
fast = fast->next->next;
pos++;
}
if (fast == NULL)total = pos * 2;
else total = pos * 2 + 1;
if (k>total) {
k = k%total;
if (!k)k = total;
}
slow = fast = head, pos = 0;
while (1) {
while (fast != end&&fast->next != end) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
if (sign) {
pos--;
}
else pos++;
}
if (fast != end&&!sign)
pos++;
if (pos == k)break;
else if (pos>k) {
sign = true;
fast = slow;
}
else {
sign = false;
fast = head;
end = slow;
slow = head;
pre = r;
}
}
pre->next = NULL;
fast = slow;
while (slow->next)slow = slow->next;
slow->next = r->next;
r->next = fast;
return r->next;
}
};