在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
解答
归并排序
由于时间限制为O(nlogn),所有使用头插入法不能达到时间要求。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
//通过以下的循环找到链表的中点,将链表分为两个部分
ListNode *slow=head,*fast=head;
while(slow->next!=NULL && fast->next!=NULL && fast->next->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
ListNode *last=slow->next;
slow->next=NULL;
ListNode *pre=sortList(head);
ListNode *las=sortList(last);
return merge(pre,las);
}
ListNode* merge(ListNode *l1 , ListNode *l2)
{
ListNode* dummy=new ListNode(0);
ListNode* p=dummy;
while(l1 && l2)
{
if(l1->val > l2->val)
{
p->next=l2;
p=p->next;
l2=l2->next;
}
else
{
p->next=l1;
p=p->next;
l1=l1->next;
}
}
//最后一定要加这两句
if(NULL==l1) p->next=l2;
if(NULL==l2) p->next=l1;
return dummy->next;
}
};
头插法
设置一个新的哑结点,不断地找到插入点,从而排序。但是时间复杂度为 O ( N 2 ) O(N^2) O(N2)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode* dummy = new ListNode(0);
ListNode* cur = head;
while(cur)
{
ListNode* temp = dummy;
while(temp->next && temp->next->val < cur->val)
{
temp = temp->next;
}
ListNode* right = temp->next;
temp->next = cur;
cur = cur->next;
temp->next->next = right;
}
return dummy->next;
}
};