[leetcode] Sort List

Sort List

/**Definition for singly-linked list.*/
#include <iostream>
using namespace std;

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;

        //使用归并排序
        ListNode *fast=head;
        ListNode *slow=head;
        ListNode *preSlow=slow;

        while(fast!=NULL&&fast->next!=NULL)
        {
            fast=fast->next->next;//移动两步
            preSlow=slow;
            slow=slow->next;//移动一步
        }

        preSlow->next=NULL;

        ListNode *ll=sortList(head);//记住当前位置,递归
        ListNode *lr=sortList(slow);

        return merge(ll,lr);
    }
    //合并
    ListNode *merge(ListNode *ll,ListNode *lr)
    {
        ListNode *p1=ll;
        ListNode *p2=lr;

        ListNode *res=new ListNode(0);
        ListNode *cur=res;

        while(p1!=NULL&&p2!=NULL)
        {
            if(p1->val<p2->val)
            {
                cur->next=p1;
                cur=cur->next;
                p1=p1->next;
            }
            else
            {
                cur->next=p2;
                cur=cur->next;
                p2=p2->next;
            }
        }

        if(p1!=NULL)
        {
            cur->next=p1;
        }
        if(p2!=NULL)
        {
            cur->next=p2;
        }
        cur=res->next;
        res->next=NULL;
        delete(res);
        return cur;
    }
};

int main()
{
    ListNode *p=new ListNode(3);
    p->next=new ListNode(4);
    p->next->next=new ListNode(1);
    Solution so;
    ListNode *res=so.sortList(p);
    cout<<res->val<<res->next->val<<res->next->next->val<<endl;
    return 0;
}


你可能感兴趣的:([leetcode] Sort List)