• 148. Sort List


    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* sortList(ListNode* head) {
            return sortList(head, NULL);
        }
        ListNode* sortList(ListNode* head, ListNode* tail) {
            if (head == tail || head->next == tail) return head;
            ListNode *halfhead = middleList(head, tail);
            ListNode *h1 = sortList(head, halfhead);
            ListNode *h2 = sortList(halfhead, tail);
            return mergeList(h1, halfhead, h2, tail);
        }
        ListNode* middleList(ListNode* head, ListNode* tail) {
            ListNode *fast = head, *slow = head;
            while (fast != tail && fast->next != tail) {
                fast = fast->next->next;
                slow = slow->next;
            }
            return slow;
        }
        ListNode* mergeList(ListNode* h1, ListNode* t1, ListNode* h2, ListNode* t2) {
            ListNode h(0);
            ListNode *p = &h;
            while (h1 != t1 && h2 != t2) {
                if (h1->val > h2->val) {
                    p->next = h2;
                    h2 = h2->next;
                }
                else {
                    p->next = h1;
                    h1 = h1->next;
                }
                p = p->next;
            }
            while (h1 != t1) {
                p->next = h1;
                h1 = h1->next;
                p = p->next;
            }
            while (h2 != t2) {
                p->next = h2;
                h2 = h2->next;
                p = p->next;
            }
            p->next = t2;  // don't forget to set last node's next to t2
            return h.next;
        }
    };
  • 相关阅读:
    AOV网和AOE网对比
    AOV网和AOE网对比
    Python类型总结
    Python数据结构
    Django之认证系统
    day22笔记
    数据库概念知识
    pymsql模块使用
    多表查询(子查询)
    多表查询(链接查询)
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9998889.html
Copyright © 2020-2023  润新知