leetcode 1669. Merge two linked lists - java implementation

Topic category

Huawei school recruitment

Link to original title

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

Please delete all the 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:

Code example: insert image description here
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.

answer

Let p1 point to 2 (the point in front of a) p2 points to 4 and then traverse p1 when p1.next = null is to traverse to the end node of list2 Let p1.next point to p2.next

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
    
    
        ListNode p1 = list1 ;
        ListNode p2 = list1 ;
        while(--a > 0){
    
    
            p1 =p1.next ;
        }
        while(b-- > 0){
    
    
            p2 = p2.next ;
        }
        
        p1.next = list2 ;
        while(p1.next != null){
    
    
            p1 = p1.next ;
        }
        p1.next = p2.next ;
        return list1 ;         
    }
}

Guess you like

Origin blog.csdn.net/qq_41810415/article/details/130318685