Merge two sorted linked lists-Java

Merge two sorted linked lists-Java

Title description

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

Example 1

enter
{1,3,5},{2,4,6}
return value
{1,2,3,4,5,6}

In fact, I don’t understand the question...you can understand it in seconds after reading the solution Write it once by yourself.

/*
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 sign = new ListNode(-1); //新建一个ListNode保存合并后得链表
        ListNode cur = sign; //用来操作的链表,每次指向下一个节点(此处需要两个ListNode是因为cur每次循环都会变化,要有一个来标记开始节点,否则会丢失)
        while(list1 != null && list2 != null){
    
     //随便一个为空都可以跳出循环了...还不理解就想如果一个链表为空,把另外一个链表剩下得拼上是不是就是合并后得
            if(list1.val <= list2.val){
    
     //值小的进入建的链表,list1指向下一个节点
                cur.next = list1;
                list1 = list1.next;
            }else{
    
    
                cur.next = list2;
                list2 = list2.next;
             }
            cur = cur.next; //cur每次循环指向下一个,这就是为什么需要sign保存开始节点
        }
        if(list1 == null){
    
    
            cur.next = list2;
        }
        if(list2 == null){
    
    
            cur.next = list1;
        }
        return sign.next;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43957211/article/details/114672231