快慢指针的使用
- 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;