1669. 合并两个链表

Difficulty
Medium
Tags
链表
URL
https://leetcode.cn/problems/merge-in-between-linked-lists/
Star
给你两个链表 list1list2 ,它们包含的元素分别为 n 个和 m 个。
请你将 list1 中下标从 ab 的全部节点都删除,并将list2 接在被删除节点的位置。
下图中蓝色边和节点展示了操作后的结果:
notion imagenotion image
请你返回结果链表的头指针。
示例 1:
notion imagenotion image
输入:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] 解释:我们删除 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
通过次数17,272提交次数22,922

法1

思路
找到两个节点
题解
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: dummy = ListNode(-1, list1) count = -1 cur = dummy # k1, k2 分别指向 a-1 和 b k1, k2 = None, None while cur: cur = cur.next count += 1 if count == a-1: k1 = cur if count == b: k2 = cur # 连接 a 位置 k1.next = list2 l2_tail = None cur = list2 while cur: l2_tail = cur cur = cur.next temp = k2.next k2.next = None # 连接 b位置 l2_tail.next = temp return dummy.next