力扣hot100 排序链表 归并排序 递归

Problem: 148. 排序链表

👩‍🏫 参考

💖 归并排序(递归)

⏰ 时间复杂度: O ( n ) O(n) O(n)

🌎 空间复杂度: O ( n ) O(n) O(n)

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 fast = head.next;
		ListNode slow = head;
		while (fast != null && fast.next != null)
		{
			slow = slow.next;
			fast = fast.next.next;
		}
		ListNode second = slow.next;
		slow.next = null;// 断开前后两段的联系
		ListNode left = sortList(head);
		ListNode right = sortList(second);
		ListNode h = new ListNode(0);
		ListNode dummy = 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 dummy.next;
	}
}
相关推荐
你撅嘴真丑1 小时前
字符环 与 变换的矩阵
算法
早点睡觉好了1 小时前
重排序 (Re-ranking) 算法详解
算法·ai·rag
gihigo19981 小时前
基于全局自适应动态规划(GADP)的MATLAB实现方案
算法
ctyshr2 小时前
C++编译期数学计算
开发语言·c++·算法
zh_xuan2 小时前
最小跳跃次数
数据结构·算法
yumgpkpm2 小时前
2026软件:白嫖,开源,外包,招标,晚进场(2025年下半年),数科,AI...中国的企业软件产业出路
大数据·人工智能·hadoop·算法·kafka·开源·cloudera
孞㐑¥3 小时前
算法—队列+宽搜(bfs)+堆
开发语言·c++·经验分享·笔记·算法
yufuu983 小时前
并行算法在STL中的应用
开发语言·c++·算法
zh_xuan3 小时前
单青蛙跳台阶
数据结构·算法
Kx_Triumphs3 小时前
计算几何-旋转卡壳两种实现方案(兼P1452题解
算法·题解