力扣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;
	}
}
相关推荐
imuliuliang6 小时前
关于数据结构在算法设计中的核心作用解析7
算法
2401_894915538 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
普通网友9 小时前
共识算法实现:从工作量证明到权益证明的演进
算法·区块链·共识算法
ldmd28410 小时前
地图生成算法(噪声篇-Perlin,Simplex,Value noise)
算法·go·地图生成
国科安芯10 小时前
FreeRTOS RISC-V 浮点上下文切换移植:在 IAR 工程中完整保存 FPU 寄存器
java·开发语言·单片机·嵌入式硬件·算法·系统架构·risc-v
小陈phd11 小时前
集成检索介绍
算法
小poop11 小时前
轮转数组:从暴力到最优,一题掌握算法复杂度分析
数据结构·算法·leetcode
樱桃读报僵尸11 小时前
说说 LLMRouter,Agent 执行过程中怎么动态的选择 LLM
算法
gis开发之家12 小时前
《Vue3 从入门到大神40篇》Vue3 源码详解(十):diff 算法全解析 —— 为什么 Vue3 比 Vue2 更快?
javascript·算法·typescript·前端框架·vue3·vue3源码