您的位置:首页 > 其它

LeetCode之“链表”:Sort List

2015-06-27 18:33 435 查看
  题目链接

  题目要求:

  Sort a linked list in O(n log n) time using constant space complexity.

  满足O(n log n)时间复杂度的有快排、归并排序、堆排序。在这里采用的是归并排序(空间复杂度O(log n)),具体程序如下:

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2)
{
ListNode *dummy = new ListNode(0);
ListNode *head = nullptr, *start = dummy;
while(l1 && l2)
{
if(l1->val < l2->val)
{
start->next = l1;
l1 = l1->next;
}
else
{
start->next = l2;
l2 = l2->next;
}
start = start->next;
}

if(!l1)
start->next = l2;
else if(!l2)
start->next = l1;

head = dummy->next;
delete dummy;
dummy = nullptr;

return head;
}

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

ListNode *slow = head, *fast = head;
ListNode *preNode = slow;
while(fast && fast->next)
{
preNode = slow;
slow = slow->next;
fast = fast->next->next;
}
preNode->next = nullptr;

ListNode *left = mergeSort(head);
ListNode *right = mergeSort(slow);
return merge(left, right);
}

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

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