您的位置:首页 > 其它

【Leet Code】148. Sort List---Medium

2015-09-15 16:13 399 查看
Sort a linkedlist in O(n log n) time using
constant space complexity.

思路:

借助2-路归并排序实现。

基本思想:

归并排序(Merging Sort)法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。

时间复杂度:O(nlog(n)),空间复杂度:O(n)。稳定排序算法。

归并排序示例:

2-路归并排序:

核心操作:将一维数组中前后相邻的两个有序序列归并为一个有序序列。

Note:在实现该算法中,对于排序使用了递归。对于非linkList,可以实现非递归,可以参考博客:http://blog.csdn.net/lili616/article/details/47701447

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeList(ListNode* beg1, ListNode* beg2)
{
if (!beg1 && !beg2 || beg1 && !beg2) return beg1;
if (!beg1 && beg2 ) return beg2;

ListNode* p1 = beg1;
ListNode* p2 = beg2;
ListNode* result = beg1;

if (p1->val > p2->val)
{
result = p2;
p2 = p2->next;
}
else
p1 = p1->next;

ListNode* curInsert = result;
while (p1 && p2)
{
while (p1 && p1->val <= p2->val)
{
curInsert->next = p1;
curInsert = p1;
p1 = p1->next;
}
while (p1 && p2 && p2->val <= p1->val)
{
curInsert->next = p2;
curInsert = p2;
p2 = p2->next;
}
}

while (p1)
{
curInsert->next = p1;
curInsert = p1;
p1 = p1->next;
}
while (p2)
{
curInsert->next = p2;
curInsert = p2;
p2 = p2->next;
}

curInsert->next = NULL;
return result;
}

ListNode* sortListRecur(ListNode* head)
{
if (!head || !head->next) return head;

ListNode* q = head;
ListNode* p = head->next;

// split the list to two lists
while (p && p->next)
{
q = q->next;
if (p->next)
p = p->next->next;
}
ListNode* head2 = q->next;
q->next = NULL;

// sort the two list first
ListNode* result1 = sortListRecur(head);
ListNode* result2 = sortListRecur(head2);

// merge list head1 with list head2
result1 = mergeList(result1, result2);
return result1;
}

ListNode* sortList(ListNode* head) {
if (!head) return head;

head = sortListRecur(head);
return head;
} };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: