【leetcode】1669. Merge In Between Linked Lists
题目如下:
You are given two linked lists:
list1andlist2of sizesnandmrespectively.Remove
list1's nodes from theathnode to thebthnode, and putlist2in 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
 
                     
                    
                 
                    
                


 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号