struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
//draw some pictures and then think it twice, just be careful when process pointers
public:
ListNode *rotateRight(ListNode *head, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode* run = head;
int len = 0;
for(; run != NULL; run = run->next, len++);
if(len == 0) return NULL;
k = k%len;
if(k == 0) return head;
ListNode* second = head;
ListNode* first = head;
while (k--)
first = first->next;
while (first->next != NULL)
{
second = second->next;
first = first->next;
}
ListNode* newHead = second->next;
second->next = NULL;
first->next = head;
return newHead;
}
};
second time
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL) return head;
int len = 0;
ListNode* tmp = head;
while(tmp != NULL) len++, tmp = tmp->next;
k = k%len;
if(k == 0) return head;
ListNode* fast = head;
ListNode* slow = head;
int i;
for(i = 0; i < k && fast != NULL; ++i) fast = fast->next;
//if(i != k-1)//...k is too large k > len?
while(fast != NULL)
{
fast = fast->next;
slow = slow->next;
}
//if(slow == head) return head;
ListNode* newHead = slow;
ListNode* oldSlow = slow;
while(slow->next != NULL) slow = slow->next;
slow->next = head;
while(slow->next != oldSlow) slow = slow->next;
slow->next = NULL;
return newHead;
}
};