/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
ListNode *fakehead = new ListNode(0);
ListNode *cur;
cur = fakehead;
while (l1 && l2)
{
if (l1->val < l2->val)
{
cur->next = l1;
cur = l1;
l1 = l1->next;
}
else
{
cur->next = l2;
cur = l2;
l2 = l2->next;
}
}
if (l1)
{
cur->next = l1;
}
else if (l2)
{
cur->next = l2;
}
return fakehead->next;
}
//6.3 Merge k Sorted Lists
ListNode *mergeKLists(vector<ListNode *> &lists)
{
if (lists.size() == 0)
return NULL;
ListNode *tmp = lists[0];
for (int i = 1; i < lists.size(); i++)
{
tmp = mergeTwoLists(tmp, lists[i]);
}
return tmp;
}
//6.5 Sort List
ListNode *sortList(ListNode *head)
{
ListNode *fast, *slow;
if (head == NULL || head->next==NULL )
return head;
fast = head; slow = head;
while (fast->next != NULL && fast->next->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
fast = slow;
slow = slow->next;
fast->next = NULL;
ListNode *firstHalf = sortList(head);
ListNode *lastHalf = sortList(slow);
return mergeTwoLists(firstHalf, lastHalf);
}
};
【LeetCode】Sort List
最新推荐文章于 2022-02-24 15:47:33 发布