Sunday, January 11, 2015

[LeetCode]Rotate List


先算出list的长度len,并且处理k,因为k有可能大于len。之后找到倒数第k + 1个节点,双指针即可。之后再重新连起来即可。时间复杂度O(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)return head;
int len = 0;
auto curr = head;
while(curr)
{
++len;
curr = curr->next;
}
k %= len;
if(!k)return head;
//find the k + 1th to the last
auto fast = head, slow = head;
while(k)
{
fast = fast->next;
--k;
}
while(fast->next)
{
fast = fast->next;
slow = slow->next;
}
//partite and reconnect
auto newNode = slow->next;
slow->next = nullptr;
fast->next = head;
return newNode;
}
};
view raw Rotate List.cpp hosted with ❤ by GitHub

No comments:

Post a Comment