

Leetcode 21 合并两个有序链表
source link: https://segmentfault.com/a/1190000040551991
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Leetcode 21 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
输入:l1 = [], l2 = []
输出:[]
输入:l1 = [], l2 = [0]
输出:[0]
从链表头开始比较,l1
与 l2
是有序递增的,所以比较 l1.val
与 l2.val
的较小值就是合并后链表的最小值,次小值就是小节点的 next.val
与大节点的 val
比较的较小值,依次递归,直到递归到 l1
、l2
均为 null
。
当递归到任意链表为 null
,直接将 next
指向另外的链表即可,不需要继续递归了。
function mergeTwoLists(l1, l2) { if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val <= l2.val) { // 如果 l1.val <= l2.val ,次小值就是 l1.next 与 l2 比较的较小值 l1.next = mergeTwoLists(l1.next, l2); return l1; } else { // 如果 l1.val > l2.val ,次小值就是 l2.next 与 l1 比较的较小值 l2.next = mergeTwoLists(l2.next, l1); return l2; } };
Recommend
-
49
1、
-
33
题目来源: 力扣(LeetCode) 题目详情: 给你两个有序整数数组 nums1 和 nums2,请你将 nums...
-
9
LeetCode 图解 | 21.合并两个有序链表-五分钟学算法 当前位置:五分钟学算法 > LeetCodeAnimation > LeetCode 图解 | 21.合并两个有序链表
-
10
LeetCode 第 21 号问题:合并两个有序链表-程序员小吴 当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 第 21 号问题:合并两个有序链表...
-
11
Leetcode 88 合并两个有序数组发布于 今天 15:13 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1...
-
9
Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析 Posted on 2021-10-07 In Java , leetcode Views: 5...
-
10
LeetCode-109-有序链表转换二叉搜索树有序链表转换二叉搜索树题目描述:给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。本题中,一...
-
17
[ 链表OJ题--C语言 ] 合并两个有序链表 原创 小白又菜 2022-05-08 19:26:30...
-
7
[leetcode]合并两个有序数组 Posted on
-
12
#yyds干货盘点# LeetCode 热题 HOT 100:合并两个有序链表 精选 原创 灰太狼_cxh ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK