Non-recursive sol, Java easy understand


  • 0
    J

    Most recursive sols are sort of slow, I am using iterative sol using merge sort algorithm.

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(0);
    		ListNode merged = dummy;
            while(l1 != null || l2!= null){
            	if(l1!= null && l2!= null && l1.val <= l2.val){
            		ListNode cur = new ListNode(l1.val);
            		merged.next = cur;
            		l1 = l1.next;
            	}
            	else if(l1!= null && l2!= null && l1.val > l2.val){
            		ListNode cur = new ListNode(l2.val);
            		merged.next = cur;
            		l2 = l2.next;
            	}
            	else if(l1 == null && l2 != null){
            		ListNode cur = new ListNode(l2.val);
            		merged.next = cur;
            		l2 = l2.next;
            	}
            	else if(l2 == null && l1 != null){
            		ListNode cur = new ListNode(l1.val);
            		merged.next = cur;
            		l1 = l1.next;
            	}
            	merged = merged.next;
            }
            return dummy.next;	
        }

Log in to reply
 

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