1ms iterative solution


  • 0
    L
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l2==null) return l1;
        if(l1==null) return l2;
        
        ListNode small, big, head;
        if(l1.val>=l2.val){
            small = l2;
            big = l1;
        }else{
            small = l1;
            big = l2;
        }
        head = small;
        while(small.next!=null){
            if(small.next.val>=big.val){
                ListNode temp = small.next;
                small.next = big;
                small = big;
                big = temp;
            }else{
                small = small.next;
            }   
        }
        small.next = big;
        
        return head;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.