leetcode - 1669. Merge In Between Linked Lists

Description

You are given two linked lists: list1 and list2 of sizes n and m respectively.

Remove list1’s nodes from the ath node to the bth node, and put list2 in their place.

The blue edges and nodes in the following figure indicate the result:

在这里插入图片描述

Build the result list and return its head.

Example 1:
在这里插入图片描述

Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
Output: [10,1,13,1000000,1000001,1000002,5]
Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.

Example 2:
在这里插入图片描述

Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
Explanation: The blue edges and nodes in the above figure indicate the result.

Constraints:

3 <= list1.length <= 10^4
1 <= a <= b < list1.length - 1
1 <= list2.length <= 10^4

Solution

No other comments, just do simulation.

Time complexity: o ( n 1 + n 2 ) o(n1+n2) o(n1+n2)
Space complexity: o ( 1 ) o(1) o(1)

Code

# 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:
        a_node, b_node = list1, list1
        b -= a - 1
        while a > 1:
            a_node = a_node.next
            a -= 1
        b_node = a_node.next
        while b > 0:
            b_node = b_node.next
            b -= 1
        a_node.next = list2
        list2_end = list2
        while list2_end.next:
            list2_end = list2_end.next
        list2_end.next = b_node
        return list1

相关推荐

  1. Leetcode 169

    2024-03-21 10:56:03       44 阅读
  2. [leetcode] 169. 多数元素

    2024-03-21 10:56:03       55 阅读
  3. leetcode 169.多数元素

    2024-03-21 10:56:03       201 阅读
  4. LeetCode 169. 多数元素

    2024-03-21 10:56:03       39 阅读
  5. leetcode-169-多数元素

    2024-03-21 10:56:03       31 阅读
  6. LeetCode169. 多数元素

    2024-03-21 10:56:03       30 阅读
  7. 多数元素算法(leetcode169题)

    2024-03-21 10:56:03       53 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-21 10:56:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-21 10:56:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-21 10:56:03       87 阅读
  4. Python语言-面向对象

    2024-03-21 10:56:03       96 阅读

热门阅读

  1. ffmpeg不常用命令整理

    2024-03-21 10:56:03       48 阅读
  2. docker基础(三)之docker rm和docker rmi

    2024-03-21 10:56:03       46 阅读
  3. 蓝队面试场景题,面试经验小记

    2024-03-21 10:56:03       39 阅读
  4. ubuntu18.04安装ffmpeg

    2024-03-21 10:56:03       36 阅读
  5. Onedrive技巧与问题

    2024-03-21 10:56:03       42 阅读
  6. vty实验

    vty实验

    2024-03-21 10:56:03      36 阅读
  7. SpringBoot 启用 Https,生成 jks 自签证书

    2024-03-21 10:56:03       42 阅读