• 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;
    }*/
    

      

  • 相关阅读:
    深入理解递归函数的调用过程
    关于字符串和字符数组的再讨论
    返回字符串的长度
    再写静态变量的有效范围
    一道关于返回指针和返回数组名的面试题
    关于TCP/IP的三次握手和四次挥手解释
    C++面向对象的编程(二)
    关于面试宝典中的检测并修改不适合的继承
    argc和argv
    基于C的文件操作(转)
  • 原文地址:https://www.cnblogs.com/zsboy/p/3877079.html
Copyright © 2020-2023  润新知