[leetcode]148. Sort List
来源:互联网 发布:矩阵分解 编辑:程序博客网 时间:2024/06/04 19:16
题目链接:https://leetcode.com/problems/sort-list/#/description
Sort a linked list in O(n log n) time using constant space complexity.
/** * Merge sort use bottom-up policy, * so Space Complexity is O(1) * Time Complexity is O(NlgN) * stable sort*/class Solution {public:ListNode *sortList(ListNode *head) {if(!head || !(head->next)) return head;//get the linked list's lengthListNode* cur = head;int length = 0;while(cur){length++;cur = cur->next;}ListNode dummy(0);dummy.next = head;ListNode *left, *right, *tail;for(int step = 1; step < length; step <<= 1){cur = dummy.next;tail = &dummy;while(cur){left = cur;right = split(left, step);cur = split(right,step);tail = merge(left, right, tail);}}return dummy.next;}private:/** * Divide the linked list into two lists, * while the first list contains first n ndoes * return the second list's head */ListNode* split(ListNode *head, int n){//if(!head) return NULL;for(int i = 1; head && i < n; i++) head = head->next;if(!head) return NULL;ListNode *second = head->next;head->next = NULL;return second;}/** * merge the two sorted linked list l1 and l2, * then append the merged sorted linked list to the node head * return the tail of the merged sorted linked list */ListNode* merge(ListNode* l1, ListNode* l2, ListNode* head){ListNode *cur = head;while(l1 && l2){if(l1->val > l2->val){cur->next = l2;cur = l2;l2 = l2->next;}else{cur->next = l1;cur = l1;l1 = l1->next;}}cur->next = (l1 ? l1 : l2);while(cur->next) cur = cur->next;return cur;}};
阅读全文
0 0
- LeetCode 148. Sort List
- [LeetCode]148.Sort List
- [leetcode] 148.Sort List
- 148. Sort List LeetCode
- Leetcode 148. Sort List
- 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 148. Sort List
- Leetcode 148. Sort List
- [LeetCode] 148. Sort List
- Leetcode-148. Sort List
- LeetCode 148. Sort List
- [LeetCode]148. Sort List
- 信息安全工程师 学习笔记(三十七)
- docker pull redis
- Java多线程编程中生产者-消费者模式的详解
- 混合笔记
- [LeetCode]367. Valid Perfect Square
- [leetcode]148. Sort List
- bzoj 2806 [Ctsc2012]Cheat
- 基于Servlet+JSP+JavaBean开发模式的用户登录注册
- 909422229_万能通用的Excel导出
- linux下fortran中编译代码时“undefined reference to `_gfortran_st_”错误
- No241. Different Ways to Add Parentheses
- 信息安全工程师 学习笔记(三十八)
- 请在微信客户端打开链接 如何解决
- javascript知识点