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;
    }
}
相关推荐
独好紫罗兰6 分钟前
对python的再认识-基于数据结构进行-a008-集合-拓展
开发语言·数据结构·python
郝学胜-神的一滴9 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
不知名XL14 小时前
day50 单调栈
数据结构·算法·leetcode
cpp_250116 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_250116 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
TracyCoder12317 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
季明洵17 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
only-qi17 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
cpp_250117 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷
浅念-17 小时前
C语言编译与链接全流程:从源码到可执行程序的幕后之旅
c语言·开发语言·数据结构·经验分享·笔记·学习·算法