Skip to content

Instantly share code, notes, and snippets.

@marklin-latte
Created April 21, 2019 08:44
Show Gist options
  • Save marklin-latte/0c0797eb30708afc0bc3e6ebdd70a7c3 to your computer and use it in GitHub Desktop.
Save marklin-latte/0c0797eb30708afc0bc3e6ebdd70a7c3 to your computer and use it in GitHub Desktop.
148. Sort List
/**
* 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) {
if(head == NULL || head->next == NULL){
return head;
}
// 使用 merge sort 的 top down 方法,才符合提題目
// time : O(nlogn)
// space : O(1)
// top down 是將 list 拆分成個位數,然後在兩兩合併
// 1. 將 list 拆分成 left(l1) 與 right(l2)
ListNode* slow = head;
ListNode* fast = head->next;
ListNode* l1;
ListNode* l2;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode* temp = slow->next;
slow->next = NULL;
l1 = head;
l2 = temp;
// merge l1 與 l2
return merge(sortList(l1), sortList(l2));
}
private:
ListNode* merge(ListNode* l1, ListNode* l2){
// 會需要一個 temp 的原因,如果沒有它 dummy 會需要一直改變
// ex. dummy = dummy->next;
// 所以需要一個 temp 來替代它。
ListNode* dummy = new ListNode(-1);
ListNode* temp = dummy;
while(l1 && l2){
if(l1->val < l2->val){
temp->next = l1;
l1 = l1->next;
}else{
temp->next = l2;
l2 = l2->next;
}
temp = temp->next;
}
if(l1) temp->next = l1;
if(l2) temp->next = l2;
return dummy->next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment