148. Sort List(鏈表歸併排序)

Sort a linked list in O(n log n) time using constant space complexity.

class Solution {
public:
    ListNode *sortList(ListNode *head) {
        if(head == NULL || head->next == NULL) {
            return head;
        }
        ListNode * slow = head;
        ListNode * fast = head;
        while(slow->next != NULL && fast->next->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode * mid = slow->next;
        slow->next = NULL;
        head = sortList(head);
        mid = sortList(mid);
        return merge(head, mid);
    }
    ListNode *merge(ListNode *headone, ListNode *headtwo) {
        if(headone == NULL) 
            return headtwo;
        if(headtwo == NULL) 
            return headone;
        ListNode * headnew = new ListNode(-1);
        ListNode * last = headnew;
        while(headone != NULL && headtwo != NULL) {
            if(headone->val < headtwo->val) {
                last->next = headone;
                headone = headone->next;
            }else {
                last->next = headtwo;
                headtwo = headtwo->next;
            }
            last = last->next;
        }
        if(headone == NULL) {
            last->next = headtwo;
        }
        if(headtwo == NULL) {
            last->next = headone;
        }
        return headnew->next;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章