简介
递归的算法很巧妙.
算法思想:
- 判断递归终止条件
- 将链表划分成两部分
- 进行递归判断左右
- 将返回的两部分头结点, 进行有序合并
- 返回 头结点
code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
// 寻找中点
ListNode * fast = head->next; ListNode *slow = head;
while(fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *tmp = slow->next; // 断开两段
slow->next = nullptr;
ListNode * left = sortList(head);
ListNode * right = sortList(tmp);
ListNode * h = new ListNode(0); // 虚头
ListNode * res = h;
while(left != nullptr && right != nullptr){
if(left->val < right-> val) {
h->next = left;
left = left->next;
} else {
h->next = right;
right = right->next;
}
h = h->next; // 进行合并, h 和 left 或 right 同步合并
}
h->next = left != nullptr ? left : right;
return res->next;
}
};
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode fast = head.next, slow = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(tmp);
ListNode h = new ListNode(0);
ListNode res = h;
while(left != null && right != null) {
if(left.val < right.val) {
h.next = left;
left = left.next;
} else {
h.next = right;
right = right.next;
}
h = h.next;
}
h.next = left != null ? left : right;
return res.next;
}
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》