您的位置:首页 > 编程语言 > C语言/C++

leetcode 148. Sort List

2017-02-25 10:14 225 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息