Leetcode: sort-list
来源:互联网 发布:知乎网络加载错误 编辑:程序博客网 时间:2024/06/11 04:14
Sorta linked list in O(n log n)time using constant space complexity.
用O(nlogn)复杂度对链表进行排序,可以采用归并排序。那么需要对链表做如下操作:
(1)将链表从中点划分为2个链表。
(2)对左链表递归的进行归并排序
(3)对右链表递归的进行归并排序
(4)合并2个链表。
举个例子:
假如有一个链表为:4->6->5->7->2->3->null
则一分为2为:(1)4->6->5->null (2)7->2->3->null
由于是个递归的过程,那么会一直划分。先递归的划分(1)左链表得到:
1)4->6->null和5->null
2)4->null和6->null。
递归到此结束,然后将4和6合并得4->6->null。再和5->null合并得到4->5->6->null。至此归并左链表排序完成。
现在递归的划分(2)右链表得到:
1)7->2->null和3->null
2)7->null和2->null
再进行合并并逆过程,得到2->7->null。再和3->null合并得到2->3->7>null。
至此,左右两个链表(4->5->6->null和2->3->7>null)都归并排序完成,合并最终的左右链表得到2->3->4->5->6->7->null。
代码如下:
ListNode *sortList(ListNode *head) { if(!head || !head->next) return head; ListNode *pre = head; ListNode *after = head->next; while(after && after->next) { pre = pre->next; after = after->next->next; } ListNode *right = pre->next; pre->next = NULL; ListNode *l = sortList(head); ListNode *r = sortList(right); return Merge(l,r); } ListNode * Merge(ListNode *left,ListNode *right) { if(!left) return right; if(!right) return left; ListNode *head = NULL; if(left->val < right->val) { head = left; head->next = Merge(left->next,right); } else if(left->val >= right->val) { head = right; head->next = Merge(left,right->next); } return head; }
阅读全文
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
- java基础 一
- Linux内核学习总结
- MFC CMFCPropertyGridCtrl控件使用问题:刷新后底部出现黑边
- AOP编程思想理解
- Automatic Inference of Search Patterns for Taint-Style Vulnerabilities
- Leetcode: sort-list
- shell编程
- 自己撸一个基于运行时注解的简单IOC框架
- 广义线性模型.多项式分布.softmax_????????????
- 激活函数
- RobotFramework学习笔记二:遇到Frame框架
- Maven与nexus关系
- [Python]
- 《数字技术》连载28:第4章 信息的寄存传输和转换 第1节 信息的编码,编码器