前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Sort List

Sort List

作者头像
用户1624346
发布2018-04-17 16:34:32
8970
发布2018-04-17 16:34:32
举报
文章被收录于专栏:calmoundcalmound

归并排序的链表法

代码语言:javascript
复制
#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;
}*/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-07-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档