148. 排序链表

题目:

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

示例1:

解题思路:

这道题是一道综合题,考察了链表中间节点+合并有序链表。首先我们链表中间节点,然后从中间结点的前一个节点处断开,分为两段链表。

然后对这两段更短的链表分别调用sortList,得到两段有序的链表。

最后合并这两段有序链表并返回结果。

详细题解可参见https://leetcode.cn/problems/sort-list/solutions/2993518/liang-chong-fang-fa-fen-zhi-die-dai-mo-k-caei

java 复制代码
/**
 * 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 head2 = middleNode(head);
        head = sortList(head);
        head2 = sortList(head2);

        return mergeTwoList(head, head2);
    }

    private ListNode middleNode(ListNode head){
        ListNode pre = head, slow = head, fast = head;
        while(fast != null && fast.next != null){
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        pre.next = null;
        return slow;
    }

    private ListNode mergeTwoList(ListNode head, ListNode head2){
        ListNode dummy = new ListNode();
        ListNode cur = dummy;
        while(head != null && head2 != null){
            if(head.val <= head2.val){
                cur.next = head;
                head = head.next;
            }else{
                cur.next = head2;
                head2 = head2.next;
            }
            cur = cur.next;
        }
        cur.next = head != null ? head : head2;
        return dummy.next;
    }
}
相关推荐
_Narcissus_15 小时前
动态规划初探(含完整代码实现)
c语言·数据结构·c++·算法·动态规划·背包问题·最短路径
_Narcissus_17 小时前
枚举和模拟算法笔记
c语言·数据结构·c++·笔记·算法·模拟·枚举
冻柠檬飞冰走茶17 小时前
《数据结构实验指导-C++语言版》 在顺序表 list 中查找元素 x
开发语言·数据结构·c++·算法·list
Brilliantwxx17 小时前
【C++】 高阶数据结构图(1)并查集
开发语言·数据结构·c++
冻柠檬飞冰走茶17 小时前
《数据结构实验指导-C++语言版》 返回单链表 list 中第 i 个元素值
开发语言·数据结构·c++·算法·list
Escalating_xu19 小时前
【C++ list 深度解析】从双向循环链表、常用接口与迭代器失效到核心模拟实现
c++·链表·list
LuminousCPP19 小时前
栈和队列专题(四):LeetCode 232. 用栈实现队列|双栈分工 + 按需迁移 + 摊还 O(1)
c语言·数据结构·笔记·算法·leetcode
纪念 22919 小时前
二叉树排序讲解(一)
数据结构
tudousisi22220 小时前
01背包8.21
数据结构·算法
小七在进步1 天前
数据结构:实现链式结构二叉树
数据结构