Ac solution code


  • 2

    We dequeue the smaller one from list l1 and l2. Pay attention to the scenario that length of l1 and l2 doesn't equal.

    Runtime complexity = O(m + n)

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
      ListNode dummyHead = new ListNode(0);
      ListNode curr = dummyHead;
      while (l1 != null && l2 != null) {
    	  if (l1.val < l2.val) { 
    	      curr.next = l1;
    	      l1 = l1.next;
    	  } else {
    	      curr.next = l2;
    	      l2 = l2.next; 
    	  }
    	  curr = curr.next;
      }
      curr.next = (l1 != null) ? l1 : l2;// Append the remaining elements in the longer list
      return dummyHead.next;
    }

Log in to reply
 

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