zoukankan      html  css  js  c++  java
  • [LeetNode]Sort List

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

    思路:分治+递归。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    private:
        int getlen(ListNode *head)
        {
            ListNode *p=head;
            int len=0;
            while(p)
            {
                len++;
                p=p->next;
            }
            return len;
        }
        ListNode* merge(ListNode *head1,ListNode *head2)
        {
            ListNode *p=head1,*q=head2,*head=NULL,*cur=NULL;
            while(p&&q)
            {
                if(p->val<=q->val)
                {
                    if(head==NULL) head=cur=p;
                    else 
                    {
                        cur->next=p;
                        cur=p;
                    }
                    p=p->next;
                }
                else
                {
                    if(head==NULL) head=cur=q;
                    else 
                    {
                        cur->next=q;
                        cur=q;
                    }
                    q=q->next;
                }
            }
            if(p) cur->next=p;
            if(q) cur->next=q;
            return head;
        }
    public:
        ListNode *sortList(ListNode *head) {
            int len=getlen(head);
            if(len==0||len==1) return head;
            ListNode *p,*q,*r;
            p=r=head;
            int halflen=len>>1;
            for(int i=0;i<halflen-1;i++) r=r->next;
            q=r->next;
            r->next=NULL;
            p=sortList(p);
            q=sortList(q);
            ListNode *newhead=merge(p,q);
            return newhead;
        }
    };
    
  • 相关阅读:
    cocos2dx进阶学习之CCDirector
    cocos2d-x游戏开发系列教程-超级玛丽03-main函数
    磁盘管理
    磁盘同步操作
    导入、导出一个卷组
    创建VG
    IBM磁盘阵列及文件系统的管理
    AIX查看HBA卡的WWN号
    AIX设备四种状态
    AIX 适配器
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3507489.html
Copyright © 2011-2022 走看看