題目描述
在O(n log n)的時間內使用常數級空間複雜度對鏈表進行排序。
Sort a linked list in O(n log n) time using constant space complexity.
思路
既然是在常數的空間複雜度,即o(1)的空間複雜度內,那麼遞歸是不能考慮了,這種情況下,只能考慮自底向上的循環方案。
代碼就在下面,要注意的幾點問題是:
- 虛擬頭結點的使用,是一個非常重要的技巧。
- 斷鏈的操作
- 合併的操作
代碼
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *sortList(ListNode *head) {
ListNode DummyHead(0);
DummyHead.next = head;
auto p = head;
// 計算鏈表長度
int length = 0;
while(p){
length += 1;
p = p->next;
}
for (int i=1; i<length; i<<=1){
auto cur = DummyHead.next;
auto tail = &DummyHead;//初始化tail存着虛節點的地址,以保證虛節點每次都能在更新後的鏈表的表頭位置。
//left = cut(q,i);
while(cur){
auto left = cur;// cut函數給定表頭和長度,返回後段的表頭。
auto right = cut(cur,i);
cur = cut(right,i);//防止找不到後面的表頭,這裏記錄下來。
tail->next = merge(left, right);//tail一直記錄已經merge好的鏈尾。起到了連接的作用。
while(tail->next){
tail = tail->next;
}
}
}
return DummyHead.next;
}
ListNode* cut(ListNode *head, int i){
auto cur = head;
while(--i && cur){
cur = cur->next;
}
if(!cur) return nullptr;
auto rightHead = cur->next;
cur->next= nullptr;
return rightHead;
}
ListNode* merge(ListNode *left, ListNode *right){
ListNode DummyHead(0);
auto p = &DummyHead;
while(left && right){
if (left->val < right->val) {
p->next = left;
p = left;
left = left->next;
}
else {
p->next = right;
p = right;
right = right->next;
}
}
p->next = left?left:right;
return DummyHead.next;
}
};