Sort List
来源:互联网 发布:淘宝联盟导购推广名称 编辑:程序博客网 时间:2024/05/16 12:03
Sort a linked list in O(n log n) time using constant space complexity.
思路:因为要用O(nlogn)的时间复杂度,用归并排序比较简单快捷。code是参考某大神的。:)
class Solution {public: ListNode *sortList(ListNode *head) { if (head == NULL || head->next == NULL) { return head; } ListNode *slow = head; ListNode *fast = head; ListNode *tail = head; while (fast != NULL && fast->next != NULL) { fast = fast->next->next; tail = slow; slow = slow->next; } tail->next = NULL; ListNode *first = sortList(head); ListNode *second = sortList(slow); head = new ListNode(0); tail = head; while (first != NULL & second != NULL) { if (first->val <= second->val) { tail->next = first; first = first->next; } else { tail->next = second; second = second->next; } tail = tail->next; } if (first != NULL) { tail->next = first; } if (second != NULL) { tail->next = second; } tail = head->next; delete head; return tail; }};
0 0
- list sort
- list sort
- Sort List
- Sort List
- list - sort
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Sort List
- Search in Rotated Sorted Array
- Linux文件系统十问
- 两种求集合所有子集的方法
- 链接服务器"(null)"的 OLE DB 访问接口 "Microsoft.Jet.OLEDB.4.0" 返回了消息 "未指定的错误"。
- 一步步写STM32 OS【三】PendSV与堆栈操作
- Sort List
- CMakeLists
- 使用dtb文件引导内核
- android网络编程 -- HTTP通信(02) Android HTTP 通信 [附源码分析]
- LinkedList与ArrayList的区别
- Qt Model/View view单元格值改变其相应的背景颜色也变
- 消息 208,级别 16,状态 1,第 1 行 对象名 '' 无效。
- 怎样用SQL Server 2008 SQL语句将Excel数据导入到数据库里指定的表里面
- Search in Rotated Sorted Array II