Why this is wrong?


  • 0
    T

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) {
      
    •     val = x;
      
    •     next = null;
      
    • }
      
    • }
      */
      public class Solution {
      public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
      if(l1 == null && l2 == null)
      return null;

       if(l1 == null) return l2;
       if(l2 == null) return l1;
       
       ListNode head;
       ListNode temp1 = l1; ListNode temp2 = l2;
       
       if(temp1.val < temp2.val){ 
           head = temp1; 
           temp1 = temp1.next;
       }
       else{
           head = temp2;
           temp2 = temp2.next;
       }
       
       ListNode newList = head.next;
       
       while(temp1 != null && temp2 != null )
       {   
           if(temp1.val < temp2.val){
               newList = temp1;
               temp1 = temp1.next;
           }
           else{
               newList = temp2;
               temp2 = temp2.next;
           }
             newList = newList.next;
       }   
       
       if(temp1 == null){
           while(temp2 != null){
               newList = temp2;
               newList = newList.next;
               temp2 = temp2.next;
           }
       }
       
       if(temp2 == null){
           while(temp1 != null){
               newList = temp1;
               newList = newList.next;
               temp1 = temp1.next;
           }
       }
       
       return head;
      

      }
      }

    It can not pass this test,

    Input: {2}, {1}
    Output: {1}
    Expected: {1,2}


Log in to reply
 

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