简介

递归的算法很巧妙.

算法思想:

  1. 判断递归终止条件
  2. 将链表划分成两部分
  3. 进行递归判断左右
  4. 将返回的两部分头结点, 进行有序合并
  5. 返回 头结点

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;
    }
}
posted on 2021-06-09 15:10  HDU李少帅  阅读(25)  评论(0编辑  收藏  举报