"Prove safety offer" - merge two sorted lists (Java)

Title Description

Two monotonically increasing input list and output list after synthesis of two lists, of course, after that we need to meet synthesis list - decreasing the rules.

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        
    }
}

Ideas: Recursive comparison, look at the specific comments in the code.

 

achieve:

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {

        //如果list1里的已经比较完了,那直接将list2剩下的返回即可
        if (list1 == null){
            return list2;
        } 

        //如果list2里的已经比较完了,那直接将list1剩下的返回即可
        if (list2 == null){
            return list1;
        }
        
        //如果list1的当前节点比list2的当前节点小,
        //则将剩余的都放在list1的当前节点后,剩余节点在后面继续比较
        if (list1.val <= list2.val){
            list1.next = Merge(list1.next,list2);
            return list1;
        }else{
        //如果list2的当前节点比list1的当前节点小,
        //则将剩余的都放在list2的当前节点后,剩余节点在后面继续比较
            list2.next = Merge(list1,list2.next);
            return list2;
        }
    }
}

 

Published 83 original articles · won praise 22 · views 2211

Guess you like

Origin blog.csdn.net/love_MyLY/article/details/103495999