0
点赞
收藏
分享

微信扫一扫

[leetcode] 148. Sort List


Description

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input:

4->2->1->3

Output:

1->2->3->4

Example 2:

Input:

-1->5->3->4->0

Output:

-1->0->3->4->5

分析

题目的意思是:常量空间复杂度排序好一个链表。

  • 找到链表中点,(快慢指针的思路),写出merge函数归并两个链表。

代码

/**
* 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(head==NULL||head->next==NULL){
return head;
}
ListNode* p=head;
ListNode* q=head->next;
while(q&&q->next){
p=p->next;
q=q->next->next;
}
ListNode* left=sortList(p->next);
p->next=NULL;
ListNode* right=sortList(head);
return mergeList(left,right);
}
ListNode* mergeList(ListNode* left,ListNode* right){
ListNode* dummy = new ListNode(0);
ListNode *p=dummy;
while(left&&right){
if(left->val<right->val){
p->next=left;
left=left->next;
}else{
p->next=right;
right=right->next;
}
p=p->next;
}
if(left){
p->next=left;
}
if(right){
p->next=right;
}
return dummy->next;
}
};

参考文献

​​[编程题]sort-list​​


举报

相关推荐

0 条评论