leetcode 148. Sort List

来源:互联网 发布:apache虚拟主机不生效 编辑:程序博客网 时间:2024/05/16 02:02
class Solution {public:ListNode* sortList(ListNode* head){if (head == nullptr || head->next == nullptr){return head;}auto fast = head->next->next, slow = head;while (fast && fast->next){slow = slow->next;fast = fast->next->next;}auto head2 = sortList(slow->next);slow->next = nullptr;return merge(sortList(head), head2);}private:ListNode* merge(ListNode* h1, ListNode* h2){auto DummyHead = new ListNode(0);auto head = DummyHead;while (h1 && h2){if (h1->val < h2->val){head->next = h1;h1 = h1->next;}else{head->next = h2;h2 = h2->next;}head = head->next;}head->next = (h1 == nullptr) ? h2 : h1;return DummyHead->next;}};

0 0
原创粉丝点击