Bull (16) Merge two sorted linked lists

//     Title description
 //     Input two monotonically increasing linked lists, and output the linked list after combining the two linked lists. Of course, we need the combined linked list to satisfy the monotonically non-decreasing rule. 
    public  static  class ListNode {
         int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

    public static ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null){
            return list2;
        }
        if(list2 ==null){
            return list1;
        }
        ListNode listNode = null ;
         if (list1.val<list2.val){ // Monotonically non-decreasing
 //             listNode.val = list1.val;
 //             Because ListNode listNode = null; just lives a reference, no object can't do val operation 
            listNode = list1;
            listNode.next = Merge(list1.next,list2);
        }else{
//            listNode.val = list2.val;
            listNode = list2;
            listNode.next = Merge(list1,list2.next);
        }
        return listNode;
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325554171&siteId=291194637