Sort List

归并排序的链表法

#include<iostream>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    ListNode* mergeLists(ListNode *a,ListNode *b)
    {
        if(a==NULL) return b;
        if(b==NULL) return a;
        ListNode *ret;
        ret = new ListNode(-1);
        ListNode *tail = ret;
        while(a && b)
        {
            if(a->val<b->val)
            {
                tail->next=a;
                a=a->next;
            }
            else
            {
                tail->next=b;
                b=b->next;
            }
            tail=tail->next;
        }
        if(a) tail->next=a;
        if(b) tail->next=b;
        ListNode *del;
        del=ret;
        ret=ret->next;
        delete del;
        return ret;
    }
    ListNode *getMid(ListNode *head)
    {
        if(!head) return NULL;
        if(!head->next) return head;

        ListNode *slow = head;
        ListNode *fast = head->next;

        while(fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    ListNode *sortList(ListNode *head)
    {
        if(!head) return NULL;
        if(!head->next) return head;

        ListNode *mid = getMid(head);
        ListNode *nextPart = NULL;
        if(mid)
        {
            nextPart = mid->next;
            mid->next = NULL;
        }

        return mergeLists(
                   sortList(head),
                   sortList(nextPart));
    }
} t;

/*ListNode* ListNodeCreate()
{
    int data;
    ListNode *ret;
    ret = new ListNode(-1);
    ListNode *tail;
    tail=ret;
    while(cin>>data)
    {
        if(data==0) break;
        ListNode *p= new ListNode(data);
        tail->next = p;
        tail =tail->next;
    }
    ListNode *del;
    del=ret;
    ret=ret->next;
    delete del;
    return ret;
}

void PrintList(ListNode *L)
{
    while(L)
    {
        cout<<L->val<<" ";
        L=L->next;
    }
}
int main()
{
    ListNode *L;
    L=ListNodeCreate();
    ListNode *T=t.sortList(L);
    PrintList(T);
    return 0;
}*/

  

posted @ 2014-07-30 07:11  calmound  阅读(568)  评论(0编辑  收藏  举报