[Leetcode] #148 Sort List
来源:互联网 发布:淘宝图书商城 编辑:程序博客网 时间:2024/06/18 14:54
Discription:
Sort a linked list in O(n log n) time using constant space complexity.
Solution:
ListNode* merge(ListNode* left, ListNode* right){if (left == NULL) return right;if (right == NULL) return left;ListNode *result = NULL;if (left->val < right->val){result = left;left = left->next;}else{result = right;right = right->next;}ListNode *curr = result;while (left && right){if (left->val < right->val){curr->next = left;left = left->next;}else{curr->next = right;right = right->next;}curr = curr->next;}curr->next = left ? left : right;return result;}ListNode* sortList(ListNode* head) {if (head == NULL || head->next == NULL) return head;ListNode *pslow = head;ListNode *pfast = head;while (pfast->next && pfast->next->next){pslow = pslow->next;pfast = pfast->next->next;}ListNode *rhalf = pslow->next;pslow->next = NULL;return merge(sortList(head), sortList(rhalf));}
//二刷ListNode *merge(ListNode *head1,ListNode *head2){ListNode *result = new ListNode(-1),*cur = result;while (head1 && head2){if (head1->val < head2->val){cur->next = head1;head1 = head1->next;}else{cur->next = head2;head2 = head2->next;}cur = cur->next;}cur->next = head1 ? head1 : head2;return result->next;}ListNode* sortList(ListNode* head) {if (!head || !head->next)return head;ListNode *pslow = head, *pfast = head->next;while (pfast && pfast->next){pfast = pfast->next->next;pslow = pslow->next;}ListNode *head2 = pslow->next;pslow->next = NULL;return merge(sortList(head), sortList(head2));}
附:Leetcode源代码见我的GitHub
0 0
- LeetCode(148)Sort List
- LeetCode: Sort List [148]
- LeetCode 148 Sort List
- [leetcode 148] Sort List
- [LeetCode 148]Sort List
- leetcode-148 Sort List
- Leetcode 148 Sort List
- LeetCode 148: Sort List
- 【leetcode 148 Sort List】
- Leetcode[148]-Sort List
- Sort List - LeetCode 148
- Leetcode# 148 Sort List
- Leetcode # 148 Sort List
- LeetCode(148) Sort List
- leetcode 148: Sort List
- [Leetcode]#148 Sort List
- 148 Sort List [Leetcode]
- LeetCode 148 Sort List
- [Leetcode] #19 Remove Nth Node From End of List
- python线程、进程与协程
- mysql忘记密码时重新设置密码
- pwnable.kr-cmd1-Writeup
- Android 利用 <activity-alias> 动态改变 App 桌面图标
- [Leetcode] #148 Sort List
- spring boot 中的application和 bootstrap
- VMware 下安装Ubuntu
- python之rabbitMQ
- 2016级ACM寒假训练(三)
- 什么是Tango事件
- 不要无形之中自己打自己的脸
- IE浏览器使用es6语法会报错:但是写vue的时候使用es5的语法还是可以渲染出来的
- UVA-818 dfs + 位运算