Sword Finger - Merge Two Sorted Lists - Double Pointer

topic description

Input two monotonically increasing linked lists, and output the linked list synthesized by the two linked lists. Of course, we need the synthesized linked list to satisfy the monotonically non-decreasing rule.

train of thought

When creating a singly linked list, a dummy node, also called a dummy node, is generally created. This is so that all nodes are guaranteed to have a predecessor node.

Regarding the use of dummy nodes :
you can refer to a cur pointer to dum, operate cur to move to complete the creation of the requested linked list, and finally return dum.next, which is the requested linked list.

The idea of ​​this question is to use double pointers to traverse the two linked lists, determine the order of adding nodes according to the size relationship, and the pointers of the two nodes advance alternately until the traversal is completed.

the code

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    
    
    public ListNode Merge(ListNode list1,ListNode list2) {
    
    
        ListNode dum = new ListNode(-1);
        ListNode cur = dum;
        
        while(list1!=null && list2!=null){
    
    
            if(list1.val <= list2.val){
    
    
                cur.next = list1;
                list1 = list1.next;
            }
            else{
    
    
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        
        if(list1!=null){
    
    
            cur.next = list1;
        }
        else{
    
    
            cur.next = list2;
        }
        return dum.next;
    }
}

Guess you like

Origin blog.csdn.net/qq_32301683/article/details/108470788