LeetCode Sort List
来源:互联网 发布:淘宝上有hm旗舰店吗 编辑:程序博客网 时间:2024/06/01 09:42
题目:
Sort a linked list in O(n log n) time using constant space complexity.
代码思想参考http://blog.csdn.net/xudli/article/details/16819545
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *sortList(ListNode *head) { return mergeSort(head); }private:ListNode *mergeSort(ListNode *head) {if(head == NULL || head->next == NULL)return head; ListNode *slow = head, *fast = head;ListNode *pre_slow = head;//分治法:使用快慢指针进行分组,slow之前为一组,之后为一组;while(fast != NULL && fast->next != NULL) {fast = fast->next->next;pre_slow = slow;slow = slow->next;}pre_slow->next = NULL;ListNode *h1 = mergeSort(head);ListNode *h2 = mergeSort(slow);return merge(h1, h2);}ListNode *merge(ListNode *h1, ListNode *h2) {ListNode *dummy = new ListNode(-1);ListNode *cur = dummy;if(h1 == NULL && h2 == NULL)return NULL;while(h1 != NULL && h2 != NULL) {if(h1->val <= h2->val) {cur->next = h1;h1 = h1->next;}else {cur->next = h2;h2 = h2->next;}cur = cur->next;}//链表h1还有剩余 while(h1 != NULL) {cur->next = h1;h1 = h1->next;cur = cur->next;}//链表h2有剩余 while(h2 != NULL) {cur->next = h2;h2 = h2->next;cur = cur->next;} cur = dummy->next;delete dummy;return cur; }};
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
- 题目1180:对称矩阵
- Resharper的使用
- 过去,现在和未来
- 对system/bin目录下可执行文件重命名操作
- 深度学习之Auto Encoder
- LeetCode Sort List
- Robot Motion
- 第八章 计时器
- 使用filter过滤器实现用户登录验证
- C++ Vector 使用心得
- HDU 1418抱歉
- 学习中
- LeetCode之Merge Sorted Array
- Cmake 学习