148. 排序链表
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
归并排序
之前我们写过一个归并排序:LeetCode之链表排序-归并排序
采用分治的思想,先写出两个链表的合并,再进行分。。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(NULL==head || NULL==head->next) return head;
ListNode* pre=head,*low=head,*fast=head;
while(fast && fast->next)
{
pre=low;
low=low->next;
fast=fast->next->next;
}
pre->next=nullptr;
return addTwo(sortList(head),sortList(low));

最低0.47元/天 解锁文章
1032

被折叠的 条评论
为什么被折叠?



