@snuffles
2019-04-10T10:19:05.000000Z
字数 968
阅读 830
链表
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
解:O(NLOGN)的排序方法包括,快排,归并,堆。根据单链表的特点,最适合用于归并排序。
//归并排序
ListNode* sortList(ListNode* head) {
// special case
if(!head || !head->next) return head;
ListNode *slow = head,*fast= head, *cur = head;
// find the middle of the link
while(fast && fast->next){
cur = slow;
slow = slow->next;
fast = fast -> next ->next;
}
cur->next = NULL;
return merge(sortList(head),sortList(slow));
}
ListNode* merge(ListNode *l1, ListNode *l2){
ListNode *dummy = new ListNode(-1);
ListNode *cur = dummy;
while(l1 && l2){
if(l1->val < l2->val){
cur->next = l1;
l1 = l1->next;
}else{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1?l1:l2;
return dummy->next;
}
//作弊sort
ListNode* sortList(ListNode* head) {
if(head==NULL) return head;
vector<int> res;
ListNode *newhead=head;
while(head->next!=NULL){
res.push_back(head->val);
head=head->next;
}
res.push_back(head->val);
sort(res.begin(),res.end());
head = newhead;
int i=0;
while(head->next!=NULL){
head->val=res[i];
head=head->next;
i++;
}
head->val=res[i];
return newhead;
}