Sort a linked list in O(n log n) time using constant space complexity.
2017-09-18 16:07
501 查看
题目链接:
https://leetcode.com/problems/sort-list/description/描述
Sort a linked list in O(n log n) time using constant space complexity.输入
输出
样例输入
样例输出
算法思想:
利用归并排序的时间复杂度为O(nlogn),进行排序源代码
class Solution { public: void FrontBackSplit(ListNode *source, ListNode **front, ListNode **back) { ListNode *slow; ListNode *fast; if (source == NULL || source->next == NULL) { *front = source; *back = NULL; } else //连表里找中点的方法:设置一个慢指针,一个快指针,慢指针一次走一步,快指针一次走2步,直到快指针结束 { slow = source; fast = source->next; while (fast!= NULL) { fast = fast->next; if (fast!= NULL) { slow = slow->next; fast = fast->next; } } *front = source; *back = slow->next; slow->next = NULL; // num++; // cout << num << endl; } } ListNode* SortedMerge(ListNode *a, ListNode *b) //对于2个链表,递归的比较链表的第一个节点,直至一个结束 { ListNode *tem = NULL; if (a==NULL) return b; else if (b==NULL) return a; if (a->val <= b->val) { tem = a; tem->next = SortedMerge(a->next, b); } else { tem = b; tem->next = SortedMerge(a, b->next); } return tem; } ListNode* sortList(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode *a, *b, *result1,*result2; FrontBackSplit(head, &a, &b); //把head 分为2部分, result1 = sortList(a); //对一部分排序 并将结果存入result1里面 result2 = sortList(b); //对另一部分排序,并将结构存入result2里面 result1 = SortedMerge(result1, result2); //对排序结果合并 return result1; } };
最优源代码
原文http://blog.csdn.net/lalor/article/details/7430624
算法复杂度:
O(nlogn)相关文章推荐
- leetcode Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- leetcode_Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity
- leetcode Sort List (Sort a linked list in O(n log n) time using constant space complexity)
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort_list——Sort a linked list in O(n log n) time using constant space complexity. 合并排序
- Reverse a doubly linked list in O(1) time
- Point-in-Time (Incremental) Recovery Using the Binary Log
- Sort a linked list using insertion sort
- leetcode_Sort a linked list using insertion sort.
- Point-in-Time (Incremental) Recovery Using the Binary Log
- [LeetCode] 148. Sort List (Linked List) - Using Quick Sort(小改动)
- leetcode上的Sort a linked list using insertion sort
- 【Leetcode】Sort List in O(nlogn) O(1)space
- bubble sort in linked list....(java version)
- Sort a linked list using insertion sort
- LeetCode234——Palindrome Linked List,O(n) time and O(1) space