先算出list的长度len,并且处理k,因为k有可能大于len。之后找到倒数第k + 1个节点,双指针即可。之后再重新连起来即可。时间复杂度O(N),常数空间。代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
}; |
No comments:
Post a Comment