码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 148 排序链表

时间:2021-06-10 17:32:08      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:rtl   nod   turn   val   tco   判断   链表   new   link   

简介

递归的算法很巧妙.

算法思想:

  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;
    }
}

leetcode 148 排序链表

标签:rtl   nod   turn   val   tco   判断   链表   new   link   

原文地址:https://www.cnblogs.com/eat-too-much/p/14866970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!