在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
思路:这个时间复杂度,肯定是要用归并排序,快速排序,堆排序之一的排序的算法。
先写归并排序: 归并排序的核心就是从中间分,分,分,然后合并。有一点要注意的是:拆分的时候有要把链表分开,借助cur指针。
C++ 代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode* merge(ListNode* l1,ListNode* l2) //相当于两个有序链表的合并
{
ListNode *start = new ListNode(0);
ListNode *tail =start;
while(l1 && l2)
{
if(l1->val < l2->val)
{
tail->next = l1;
l1=l1->next;
}
else{
tail->next =l2;
l2 = l2->next;
}
tail =tail->next;
}
if(l1) tail->next = l1;
if(l2) tail->next = l2;
return start->next;
}
public:
ListNode* sortList(ListNode* head) { //有一个问题在于要把链表从中间断开
if(!head ||!head->next) return head;
//找到中间结点
ListNode *fast=head , *slow=head, *cur=NULL;
while(fast && fast->next)
{
cur = slow;
fast=fast->next->next;
slow= slow->next;
}
cur->next = NULL;
return merge(sortList(head),sortList(slow));
}
};