• 【leetcode】1669. Merge In Between Linked Lists


    题目如下:

    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 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
    Output: [0,1,2,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 <= 104
    • 1 <= a <= b < list1.length - 1
    • 1 <= list2.length <= 104

    解题思路:题目不难,先找出list2的头和尾,然后遍历list1,在指定的位置分别指向list2的头尾即可。

    代码如下:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution(object):
        def mergeInBetween(self, list1, a, b, list2):
            """
            :type list1: ListNode
            :type a: int
            :type b: int
            :type list2: ListNode
            :rtype: ListNode
            """
            l2_head = list2
            l2_tail = None
            while list2 != None:
                l2_tail = list2
                list2 = list2.next
    
            inx = 1
    
    
            head = list1
    
            while list1 != None:
                if a == inx :
                    tmp = list1.next
                    list1.next = l2_head
                    list1 = tmp
                if b == inx :
                    l2_tail.next = list1.next
                    break
                list1 = list1.next
                inx += 1
            return head
  • 相关阅读:
    接口的显示实现和隐式实现
    Math.Round和四舍五入
    经典SQL语句大全(转)
    简明添加log4net到项目中
    NAnt学习笔记(3) Properties, Loggers & Listeners
    (转)Groupon前传:从10个月的失败作品修改,1个月找到成功
    Pyramid中如何配置多种URL匹配同一个View
    《IT项目管理》读书笔记(4) —— 项目范围管理
    C#语法糖
    枚举类型转换成字符串
  • 原文地址:https://www.cnblogs.com/seyjs/p/15861188.html
Copyright © 2020-2023  润新知