leetcode1669. Merge In Between Linked Lists

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1669. 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

 

以上是关于leetcode1669. Merge In Between Linked Lists的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Algorithm 1669. 合并两个链表

LeetCode Algorithm 1669. 合并两个链表

LeetCode Algorithm 1669. 合并两个链表

LeetCode SQL 1669. 176. 第二高的薪水

leetcode - Merge Two Sorted Lists

1669. 合并两个链表