天天看點

LeetCode_148. Sort List

題目描述:

LeetCode_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)
            return head;
        vector<int> sortVec;
        ListNode* p=head;
        while(p){
            sortVec.push_back(p->val);
            p=p->next;
        }
        sort(sortVec.begin(),sortVec.end());
        p=head;
        int i=0;
        while(p){
            p->val=sortVec[i++];
            p=p->next;
        }
        return head;
    }
};      
/**
 * 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;
        return merge(head);
    }
    ListNode* merge(ListNode* &head){
        if(head==NULL||head->next==NULL)
            return head;
        ListNode *fast, *slow;//使用快慢指針将連結清單均分
        ListNode *pre;
        fast=slow=head;
        while(fast){
            pre=slow;
            slow=slow->next;
            fast=fast->next;
            if(fast)//在移動快指針的時候需要注意第二次移動的方式
                fast=fast->next;
        }
        pre->next=NULL;
        ListNode *l,*r;
        l=merge(head);
        r=merge(slow);
        return mergeSort(l,r);
    }
    ListNode* mergeSort(ListNode* &l,ListNode* &r){
        //這種建立新連結清單的方法需要學會,先建立一個頭結點,最後再将這個頭結點删除
        ListNode* pRes=new ListNode(0);
        ListNode* p=pRes;
        while(l&&r){
            if(l->val<=r->val){
                p->next=l;
                l=l->next;
            }else{
                p->next=r;
                r=r->next;
            }
            p=p->next;
        }
        if(l)
            p->next=l;
        if(r)
            p->next=r;
        p=pRes->next;
        delete pRes;
        return p;
    }
};