This is my Java code


  • 0
    K
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        
      ListNode head = new ListNode(0);  //I need a head, but the result dosen't neet it
    	
    	ListNode temp = head;
    	 ListNode p = l1;
         ListNode q = l2;
         while(p!=null && q != null){
             
             if(p.val < q.val){
                 temp.next = p;
                 p = p.next;
                 temp = temp.next;
             }else{
                 temp.next = q;
                 q = q.next;
                 temp = temp.next;
             }
         }
         
         while(p != null){
             temp.next = p;
             p = p.next;
             temp = temp.next;
         }
         
         while(q != null){
             temp.next = q;
             q = q.next;
             temp = temp.next;
         }
         
         
         return head.next; 
    }

  • 0
    L

    When you reach end of one list, you don't need to go through the other list, it's sorted and can be linked directly to the end. So instead of two last whiles, we only need:
    temp.next = (p != null) ? p : q;


Log in to reply
 

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