力扣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;
	}
}
相关推荐
weixin_4588726110 分钟前
东华复试OJ二刷复盘2
算法
Charlie_lll11 分钟前
力扣解题-637. 二叉树的层平均值
算法·leetcode
爱淋雨的男人20 分钟前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn32 分钟前
模拟题刷题3
java·数据结构·算法
滴滴答滴答答1 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
圣保罗的大教堂1 小时前
leetcode 1980. 找出不同的二进制字符串 中等
leetcode
Neteen1 小时前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法
礼拜天没时间.1 小时前
力扣热题100实战 | 第25期:K个一组翻转链表——从两两交换到K路翻转的进阶之路
java·算法·leetcode·链表·递归·链表反转·k个一组翻转链表
Swift社区2 小时前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展
再难也得平2 小时前
力扣239. 滑动窗口最大值(Java解法)
算法·leetcode·职场和发展