Leetcode -- Sort List
来源:互联网 发布:青少年使用网络调查 编辑:程序博客网 时间:2024/05/16 10:32
题目:
Sort a linked list in O(n log n) time using constant space complexity.
分析:
O(n log n)有归并排序,快速排序和堆排序。针对链表,采用归并排序是比较合理的。快排在最坏的情况,复杂度是O(n^2)。
思路:难点在于寻找链表的中点。
代码:
ListNode* sortList(ListNode* head) { //如果head是空的,或者只有一个node,就不需要排序了 if (head == NULL ||head -> next == NULL) return head; //fast, slow配合寻找中点。 ListNode* fast = head; ListNode* slow = head; while(fast->next && fast->next->next) { slow = slow -> next; fast = fast ->next->next; } fast = slow; slow = fast -> next; fast->next = NULL; fast = sortList(head); slow = sortList(slow); return merge(fast, slow); } //将两个排好序的链表,合成一个。 ListNode* merge(ListNode* head1, ListNode* head2) { if(head1 == NULL) return head2; if(head2 == NULL) return head1; ListNode* l; if(head1->val > head2 -> val) { l = head2; head2 = head2->next; } else { l = head1; head1= head1->next; } ListNode* l1 = l; while(head1 && head2) { if(head1->val > head2 -> val) { l->next = head2; head2 = head2 -> next; l = l-> next; } else { l-> next = head1; head1 = head1 -> next; l = l->next; } } if(head1) { l->next = head1; } if(head2) { l->next = head2; } return l1; }
0 0
- [leetcode][list][sort] Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode: Sort List
- Sort List | leetcode
- leetcode-Sort List
- leetcode-Insertion Sort List
- LeetCode题解:Sort List
- leetcode 134: Sort List
- [LeetCode]Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Sort List
- 【LeetCode】Insertion Sort List
- leetCode - Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- Boostrap入门+样式学习--壹--
- hdu5386Cover六校(想法题)
- 换路定则
- 九度 Online Judge 算法 刷题 题目1058:反序输出
- [leetcode-136]Single Number(c)
- Leetcode -- Sort List
- 用 ES6 generator & Promise 写异步代码
- java1.8不能生成classes.dex
- hdu-5372 Segment Game(离散树状数组)(2015多校contest 7)
- MyEclipse 项目部署到tomcat时出现错误之——deploy
- dup,dup2,2>&1,tee用法
- OC - Method
- 自组织特征映射神经网络(SOFM)
- 九度 Online Judge 算法 刷题 题目1059:abc