Leetcode-One question per day [1669. Merge two linked lists]

topic

You are given two linked lists list1 and list2 containing n and m elements respectively.

Please delete all nodes with subscripts from a to b in list1, and connect list2 to the position of the deleted nodes.

The blue edges and nodes in the figure below show the result of the operation:

 

Please return the head pointer of the result linked list.

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 delete the two nodes whose subscripts are 3 and 4 in list1, and connect list2 to this position . The blue edges and nodes in the above figure are the answer list. 

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 are the answer list.

hint:

  • 3 <= list1.length <= 104
  • 1 <= a <= b < list1.length - 1
  • 1 <= list2.length <= 104

 

problem solving ideas

Take a chestnut:

Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5,

           list2 = [1000000,1000001,1000002,1000003,1000004]

1. We first set a prev and last to traverse list1, find the ath node and b-1th node of list1

 

 

 

 

 

 

 

 2. After finding it, we set a node last1 pointing to last.next, which is our b node.

3. Then set last.next = null to disconnect the node we need to delete.

 

4. Set another last2 to find the tail node of the list2 list

 

 

 

 

 

5. Now we connect the linked list and we are done.

      prev.next = list2;
      last2.next = last1;
      return list1; 

  

 

 

Code

class Solution {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        ListNode prev = list1;
        for(int i = 1; i < a; i++){
            prev = prev.next;
        }
        ListNode last = list1;
         for(int j = 0; j < b; j++){
            last = last.next;
        }
        ListNode last1 = last;
        last1 = last1.next;
        last.next = null;
        ListNode last2 = list2;
        while(last2.next != null){
            last2 = last2.next;
        }
        prev.next = list2;
        last2.next = last1;
        return list1;
    }
}

Test Results

 

 

Guess you like

Origin blog.csdn.net/lucky_1314520/article/details/131578638