Here's a non-recursive solution using Java


  • 0
    J
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null){
                return l2;
            }
            if(l2 == null){
                return l1;
            }
            ListNode resultNode, curNode, tmpNode;
            if(l1.val <= l2.val){
                curNode = l1;
                l1 = l1.next;
            } else {
                curNode = l2;
                l2 = l2.next;
            }
            resultNode = curNode;
            while(l1!=null && l2!=null){
                if(l1.val <= l2.val){
                    tmpNode = l1.next;
                    curNode.next = l1;
                    l1 = tmpNode;
                } else {
                    tmpNode = l2.next;
                    curNode.next = l2;
                    l2 = tmpNode;
                }
                curNode = curNode.next;
            }
            if(l1!=null){
                curNode.next = l1;
            }
            if(l2!=null){
                curNode.next = l2;
            }
    
            return resultNode;
        }
    

Log in to reply
 

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