LeetCode 148:Sort List
来源:互联网 发布:linux操作系统入门书籍 编辑:程序博客网 时间:2024/05/19 20:22
Sort a linked list in O(n log n) time using constant space complexity.
//题目要求:对链表进行排序//解题思路:归并排序,再Merge//归并排序的基本思想是:找到链表的中间节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个排好序的链表进行Merge class Solution { public: ListNode* sortList(ListNode* head) { if (head == NULL || head->next == NULL) return head; //快慢指针找到中间节点 ListNode *fast = head, *slow = head; while (fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; slow = slow->next; } //断开 fast = slow; slow = slow->next; fast->next = NULL; ListNode *l1 = sortList(head); //前半段排序 ListNode *l2 = sortList(slow); //后半段排序 return mergeTwoLists(l1, l2); } //Merge Two Sorted Lists ListNode *mergeTwoLists(ListNode *l1, ListNode *l2){ ListNode dummy(-1); for (ListNode* p = &dummy; l1 != NULL || l2 != NULL; p = p->next) { int val1 = l1 == NULL ? INT_MAX : l1->val; int val2 = l2 == NULL ? INT_MAX : l2->val; if (val1 <= val2) { p->next = l1; l1 = l1->next; } else { p->next = l2; l2 = l2->next; } } return dummy.next; } };
1 1
- LeetCode(148)Sort List
- LeetCode: Sort List [148]
- LeetCode 148 Sort List
- [leetcode 148] Sort List
- [LeetCode 148]Sort List
- leetcode-148 Sort List
- Leetcode 148 Sort List
- LeetCode 148: Sort List
- 【leetcode 148 Sort List】
- Leetcode[148]-Sort List
- Sort List - LeetCode 148
- Leetcode# 148 Sort List
- Leetcode # 148 Sort List
- LeetCode(148) Sort List
- leetcode 148: Sort List
- [Leetcode]#148 Sort List
- 148 Sort List [Leetcode]
- LeetCode 148 Sort List
- 【Windows Form 实战】学生成绩管理系统(三) 公共类Data.cs
- IOS开发基础Object-C(13)—— protocol协议
- ubuntu常用快捷键记录
- xendesktop7.6虚拟桌面U盘重定向
- C#版及nodejs版的com端口监听程序
- LeetCode 148:Sort List
- OC为什么需要copy
- 使用Windbg解析dump文件
- 两标关联update
- 2016, 新的一年,新的起点
- [easyui]单例模式封装组件,提高性能,按需使用
- 机器学习(三):分类算法之决策树算法
- 20160103
- poj 1144 Network