LeetCode 148. 排序链表

使用归并排序的思想

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
public:
    //使用归并排序
    void merge(ListNode* &head, ListNode* &mid, ListNode* &end){
	if(head==mid && mid==end)
            return;

        ListNode* p=head, *p1=mid->next;
        vector<int> valList;
        int K=0;
        while(p!=mid->next && p1!=end->next){
            if(p->val<=p1->val){
                valList.push_back(p->val);
                K++;
                p=p->next;
            }
            else{
                valList.push_back(p1->val);
                K++;
                p1=p1->next;
            }
        }
        while(p!=mid->next){
            valList.push_back(p->val);
            K++;
            p=p->next;
        }
        
         while(p1!=end->next){
             valList.push_back(p1->val);
             K++;
             p1=p1->next;
        }

        ListNode* p2=head;
        for(int k=0;k<K;++k){
            p2->val=valList[k];
            p2=p2->next;
        }
    }
    
    void mergeSort(ListNode* &head, ListNode* &end){
	if(head==end)
	    return;

        ListNode* pfast=head, *pslow=head;
        while(pfast!=end){
            if(pfast->next!=end)
                pfast=pfast->next->next;
	    else
		break;
	    pslow=pslow->next;
        }
        
        
        ListNode* pmid=pslow;//利用快慢指针查找中间节点
        if(head!=pmid)
            mergeSort(head, pmid);
        if(pmid!=end)
            mergeSort(pmid->next, end);
        
        merge(head, pmid, end);
    }
    
    ListNode* sortList(ListNode* head) {
        if(head==NULL || head->next==NULL)
            return head;
        
        ListNode* end=head;
	while(end->next!=NULL)
	    end=end->next;

        mergeSort(head, end);
        
        return head;
    }
};


猜你喜欢

转载自blog.csdn.net/sinat_15723179/article/details/80883410