1. 程式人生 > >148 Sort List 鏈表上的歸並排序和快速排序

148 Sort List 鏈表上的歸並排序和快速排序

UC 快速排序 歸並 get int key 方法 struct pos

在使用O(n log n) 時間復雜度和常數級空間復雜度下,對鏈表進行排序。

詳見:https://leetcode.com/problems/sort-list/description/

方法一:歸並排序

/**
 * 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==nullptr||head->next==nullptr)
        {
            return head;
        }
        ListNode* slow=head;
        ListNode* fast=head;
        ListNode* mid=nullptr;
        while(fast&&fast->next)
        {
            mid=slow;
            slow=slow->next;
            fast=fast->next->next;
        }
        mid->next=nullptr;
        return mergeHelper(sortList(head),sortList(slow));
    }
    ListNode* mergeHelper(ListNode* low,ListNode* high)
    {
        ListNode* helper=new ListNode(-1);
        ListNode* cur=helper;
        while(low&&high)
        {
            if(low->val<high->val)
            {
                cur->next=low;
                low=low->next;
            }
            else
            {
                cur->next=high;
                high=high->next;
            }
            cur=cur->next;
        }
        cur->next=low?low:high;
        return helper->next;
    }
};

方法二:快速排序

/**
 * 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==nullptr||head->next==nullptr)
        {
            return head;
        }
        quickSort(head,nullptr);
        return head;
    }
    void quickSort(ListNode* begin,ListNode* end)
    {
        if(begin!=end)
        {
            ListNode* sep=getSeperator(begin,end);
            quickSort(begin,sep);
            quickSort(sep->next,end);
        }
    }
    ListNode* getSeperator(ListNode* begin,ListNode* end)
    {
        ListNode* first=begin;
        ListNode* second=begin->next;
        int key=begin->val;
        while(second!=end)
        {
            if(second->val<key)
            {
                first=first->next;
                swap(first,second);
            }
            second=second->next;
        }
        swap(first,begin);
        return first;
    }
    void swap(ListNode* a,ListNode* b)
    {
        int tmp=a->val;
        a->val=b->val;
        b->val=tmp;
    }
};

148 Sort List 鏈表上的歸並排序和快速排序