zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    按钮设计
    图标设计
    滤镜与通道
    路径、形状工具与选区
    类的无参方法
    类和对象
    阅读器关闭时尝试调用Read无效时的解决方法
    进入ASP .net mvc的世界
    linux命令-vim
    linux命令-分区表fstab
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9998889.html
Copyright © 2011-2022 走看看