1669. 合并两个链表 (Python 实现)

x33g5p2x  于2022-07-13 转载在 Python  
字(1.2k)|赞(0)|评价(0)|浏览(431)

题目:
给你两个链表 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]
解释:上图中蓝色的边和节点为答案链表。

代码:

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, val=0, next=None):
  4. # self.val = val
  5. # self.next = next
  6. class Solution:
  7. def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
  8. i = list1
  9. res = ListNode()
  10. temp = res
  11. for _ in range(a):
  12. temp.next = i
  13. temp = temp.next
  14. i = i.next
  15. while list2:
  16. temp.next = list2
  17. temp = temp.next
  18. list2 = list2.next
  19. for _ in range(a,b+1):
  20. i = i.next
  21. temp.next = i
  22. return res.next
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, val=0, next=None):
  4. # self.val = val
  5. # self.next = next
  6. class Solution:
  7. def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
  8. i = list1
  9. temp = 0
  10. while list1:
  11. if temp == a-1:
  12. start = list1
  13. elif temp == b+1:
  14. end = list1
  15. list1 = list1.next
  16. temp += 1
  17. start.next = list2
  18. while list2.next:
  19. list2 = list2.next
  20. list2.next = end
  21. return i

相关文章