61. Rotate List

来源:互联网 发布:知乎怎么匿名 编辑:程序博客网 时间:2024/06/13 23:12

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.

思路:注意k有可能大于n。然后就是用快慢指针。

/** * 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 || head->next == NULL || k == 0) return head;        int length = 0;        ListNode* tmp = head;        while(tmp != NULL)        {            tmp = tmp->next;            length++;        }        int n = k%length;  //k有可能大于n        if(n == 0) return head;        ListNode* fast = head;        for(int i = 0; i < n; i++)        {            fast = fast->next;        }        ListNode* slow = head;        while(fast->next !=NULL)        {            fast = fast->next;            slow = slow->next;        }        fast->next = head;        head = slow->next;        slow->next = NULL;        return head;    }};
0 0