My Accepted Iterative approach


  • 0
    S
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
     /* Check for null inputs  */
            if(l1 == null)  return l2;
            if(l2 == null)  return l1;
        /*Identify the smallest and mark it as head */    
            ListNode head = l1.val < l2.val ? l1: l2;
            ListNode nextNode = head;
            if(head == l1)  l1 = l1.next;
            else l2 = l2.next;
    /* Iterate and compare the values of nodes while fixing the references */
            while(l1 != null && l2 != null){
                if(l1.val < l2.val){
                   nextNode.next = l1;
                    l1= l1.next;
                }
                else{
                    nextNode.next = l2;
                    l2 = l2.next;
                }
                nextNode = nextNode.next;
            }
    /* If the exit condition is due to l2 only, add the remaining nodes from l1 */
            if(l1 != null)  nextNode.next = l1;
    /* If the exit condition is due to l1 only, add the remaining nodes from l2 */
            else if(l2 != null)  nextNode.next = l2;
            return head;
        }
    

Log in to reply
 

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