LeetCode之“链表”:Sort List
2015-06-27 18:33
435 查看
题目链接
题目要求:
Sort a linked list in O(n log n) time using constant space complexity.
满足O(n log n)时间复杂度的有快排、归并排序、堆排序。在这里采用的是归并排序(空间复杂度O(log n)),具体程序如下:
题目要求:
Sort a linked list in O(n log n) time using constant space complexity.
满足O(n log n)时间复杂度的有快排、归并排序、堆排序。在这里采用的是归并排序(空间复杂度O(log n)),具体程序如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* merge(ListNode* l1, ListNode* l2) { ListNode *dummy = new ListNode(0); ListNode *head = nullptr, *start = dummy; while(l1 && l2) { if(l1->val < l2->val) { start->next = l1; l1 = l1->next; } else { start->next = l2; l2 = l2->next; } start = start->next; } if(!l1) start->next = l2; else if(!l2) start->next = l1; head = dummy->next; delete dummy; dummy = nullptr; return head; } ListNode* mergeSort(ListNode* head) { if(!head->next) return head; ListNode *slow = head, *fast = head; ListNode *preNode = slow; while(fast && fast->next) { preNode = slow; slow = slow->next; fast = fast->next->next; } preNode->next = nullptr; ListNode *left = mergeSort(head); ListNode *right = mergeSort(slow); return merge(left, right); } ListNode* sortList(ListNode* head) { if(!head || !head->next) return head; return mergeSort(head); } };
相关文章推荐
- HDU 1018 Big Number (阶乘位数)
- 超级2048
- 最长公共子序列的另一类优化方法
- python单线程网络爬虫
- ffmpeg截取一段视频中一段视频
- 黑马程序员-------java语法基础
- Android 音频焦点(Audio Focus)
- 字符串的全排列详解
- cocoapods工程路径变更后library not found解决方案
- 让所有正在播放音乐的播放器主动停止播放
- hive面试题目:表大概有2T左右,对表数据转换--2
- hive面试题目:表大概有2T左右,对表数据转换
- 视图加载时自动执行铵钮事件
- 程序员的修养
- java web学习
- Android的canvas.rotate()与canvas.translate研究
- 实现类似Tumblr的Title Bar跟随滑动渐变的效果
- 动态规划--凸多边形最优三角剖分
- 获取html节点时过滤空白节点
- Cordys 流程启动与结束调用了哪些WebService