「每日LeetCode」2023年1月30日

本文最后更新于:2023年3月19日 晚上

1669.合并两个链表

1669.合并两个链表

Category Difficulty Likes Dislikes
algorithms Medium (74.95%) 71 -

Tags
Companies
给你两个链表 list1 和 list2 ,它们包含的元素分别为 n 个和 m 个。
请你将 list1 中下标从 a 到 b 的全部节点都删除,并将 list2 接在被删除节点的位置。
下图中蓝色边和节点展示了操作后的结果:

请你返回结果链表的头指针。

示例 1:

输入:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] 输出:[0,1,2,1000000,1000001,1000002,5] 解释:我们删除 list1 中下标为 3 和 4 的两个节点,并将 list2 接在该位置。上图中蓝色的边和节点为答案链表。
示例 2:
输入:list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] 输出:[0,1,1000000,1000001,1000002,1000003,1000004,6] 解释:上图中蓝色的边和节点为答案链表。

提示:

  • 3 <= list1.length <= 104
  • 1 <= a <= b < list1.length - 1
  • 1 <= list2.length <= 104

Discussion | Solution

思路

按题意模拟即可

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* @lc app=leetcode.cn id=1669 lang=javascript
*
* [1669] 合并两个链表
*/

// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {number} a
* @param {number} b
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeInBetween = function (list1, a, b, list2) {
let cur = list1;
let temp;
let count = 1;
while (cur && cur.next && count !== a) {
cur = cur.next;
count++;
}
temp = cur.next;
cur.next = list2;
while (temp && count !== b) {
temp = temp.next;
count++;
}
while (cur && cur.next) cur = cur.next;
cur.next = temp.next;
temp.next = null;
return list1;
};
// @lc code=end