LeetCode--insertion-sort-list
2016-04-06 21:14
267 查看
题目描述
Sort a linked list in O(n log n) time using constant space complexity.
解题思路:
1,归并排序
Sort a linked list in O(n log n) time using constant space complexity.
解题思路:
1,归并排序
class Solution { public: ListNode* findMiddle(ListNode* head){ ListNode* chaser = head; ListNode* runner = head->next; while(runner != NULL && runner->next != NULL){ chaser = chaser->next; runner = runner->next->next; } return chaser; } ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL){ return l2; } if(l2 == NULL){ return l1; } ListNode* dummy = new ListNode(0); ListNode* head = dummy; while(l1 != NULL && l2 != NULL){ if(l1->val > l2->val){ head->next = l2; l2 = l2->next; } else{ head->next = l1; l1 = l1->next; } head = head->next; } if(l1 == NULL){ head ->next = l2; } if(l2 == NULL){ head->next = l1; } return dummy->next; } ListNode* sortList(ListNode* head) { if(head == NULL || head ->next == NULL){ return head; } ListNode* middle = findMiddle(head); ListNode* right = sortList(middle->next); middle -> next = NULL; ListNode* left = sortList(head); return mergeTwoLists(left, right); } };
相关文章推荐
- 最简实例说明WAIT、NOTIFY、NOTIFYALL的使用方法
- 前端开发曾经遇到的那些小困惑
- XenServer 6.5 For Install Update
- 打印星号图
- Filter介绍
- Swift中UITabBarController图片去除渲染
- crm操作货币实体
- 复利计算器5.0
- container docker
- zabbix_agentd.conf配置文件详解
- C++走向远洋——32(项目一内全部成员函数)
- ios定位
- J友
- centos卸载rpm包的方法
- Nginx性能优化----系统篇
- nyoj 73比大小
- 6、Mysql的数据库的备份和还原
- CSS利用padding和margin正负相消实现多列等高
- HDU-2546 饭卡 ( 01背包 )
- centos卸载rpm包的方法