/**
* 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) {
ListNode* fast = head, *slow = head;
int len = 0;
while(fast != NULL){
++len;
fast = fast->next;
}
if(k == 0 || len == 0){
return head;
}
k %= len;
int cnt = 0;
fast = head;
while(cnt < k){
fast = fast->next;
++cnt;
}
while(fast->next != NULL){
fast = fast->next;
slow = slow->next;
}
fast->next = head;
head = slow->next;
slow->next = NULL;
return head;
}
};
leetcode Rotate List
最新推荐文章于 2019-04-16 21:05:39 发布