题目描述
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
思路
快慢指针找中间结点,迭代法(注释)或递归法合并链表。
代码
/**
* 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* fast = head;
ListNode* slow = head;
ListNode* slow2 = NULL;
while(fast && fast->next){
slow2 = slow;
slow = slow->next;
fast = fast->next->next;
}
slow2->next = NULL;
ListNode* l1 = sortList(head);
ListNode* l2 = sortList(slow);
return merge(l1, l2);
}
ListNode* merge(ListNode* l1, ListNode* l2) {
// if(!l1) return l2;
// if(!l2) return l1;
// ListNode* p = new ListNode(0);
// ListNode* start = p;
// while(l1 && l2){
// if(l1->val < l2->val){
// p->next = l1;
// l1=l1->next;
// }else{
// p->next = l2;
// l2=l2->next;
// }
// p = p->next;
// }
// if(!l1)
// p->next = l2;
// else
// p->next = l1;
// return start->next;
if(!l1) return l2;
if(!l2) return l1;
if(l1->val < l2->val) {
l1->next = merge(l1->next, l2);
return l1;
} else {
l2->next = merge(l2->next, l1);
return l2;
}
}
};