合并两个有序链表,合并后仍有序

版权声明:禁止侵权,打击盗版! https://blog.csdn.net/ChenGX1996/article/details/82120911
//输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        //假如某一或两个链表为空
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        if(list1 == null && list2 == null){
            return null;
        }
        
        ListNode pNode = null;
        if(list1.val < list2.val){
            pNode = list1;
            //运用递归
            pNode.next = Merge(list1.next,list2);
        }else{
            pNode = list2;
            pNode.next = Merge(list1,list2.next);
        }
        return pNode;
    }
}

猜你喜欢

转载自blog.csdn.net/ChenGX1996/article/details/82120911