[LeetCode] Sort List 排序 sort

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

 

Hide Tags
  Linked List Sort
 

  基于单项链表的排序,时间为nlogn ,O(1)空间,其实及将数组的快速排序用链表实现,并用递归来维护拆分与合并。
#include <iostream>

using namespace std;



/**

 * 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 NULL;

        if(head->next==NULL)    return head;

        ListNode *plft=head,*prgt=head;

        while(prgt->next!=NULL){

            if(prgt->next!=NULL)  prgt=prgt->next;

            if(prgt->next!=NULL)  prgt=prgt->next;

            plft = plft->next;

        }

        if(prgt==head->next){

            if(head->val>prgt->val){

                prgt->next = head;

                head->next = NULL;

                head = prgt;

            }

            return head;

        }

        prgt = plft->next;

        plft->next = NULL;

        plft = sortList(head);

        prgt = sortList(prgt);

        ListNode * ret,*leave,*tmp,*tmp2;

        ret = plft->val<=prgt->val?plft:prgt;

        tmp = ret;

        leave = plft->val<=prgt->val?prgt:plft;

        while(leave!=NULL){

            while(tmp->next!=NULL&&tmp->next->val<=leave->val)  tmp= tmp->next;

            if(tmp->next==NULL){

                tmp->next = leave;

                break;

            }

            tmp2 = leave->next;

            leave->next = tmp->next;

            tmp->next = leave;

            leave = tmp2;

        }

        return ret;

    }

};

//

int main()

{

    ListNode n1(3),n2(5),n3(2),n4(8),n5(6),n6(0),n7(4);

    n1.next=&n2;

    n2.next=&n3;

    n3.next=&n4;

    n4.next=&n5;

    n6.next=&n7;

    n5.next=&n6;

    Solution sol;

    ListNode * ret = sol.sortList(&n1);

    ListNode * p = ret;

    while(p!=NULL){

        cout<<p->val<<" ";

        p = p->next;

    }

    cout<<endl;

    return 0;

}

 

你可能感兴趣的:(LeetCode)