Does any one know why this fails.


  • 0
    V
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
      if(null == l1 ) return l2;
      if(null == l2)  return l1; 
      
      ListNode tempHead = new ListNode(0);
      
      ListNode temp =  tempHead;
      
      while(l1!=null || l2!=null){
          
          
          
          boolean flag = false;
         
          if(l1!=null){
          
          temp.val = l1.val;
          
          l1 = l1.next;
          
          flag =  true;
          
          }
          
          if(l2!=null){
          
          temp.val = temp.val +  l2.val;
          
          l2 = l2.next;
          
          flag = true;
          
           }
          
           
           //temp .next = new ListNode(0);
          // temp = temp.next;
           
          
          }
      
      return tempHead;
        
    }

  • 0
    V

    Flag is used to mark if previous nodes' sum is greater than 0 ; In the code flag is set without checking this condition and flag is set but never used.Memory allocation need to be done for all the nodes in the output sum linked list, but in the code space is allocated only for head node. In every iteration of the loop temp node(which stores resultant sum) must be updated with temp.next Please find this below code with modifications

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
           int carry =0;
     
            ListNode newHead = new ListNode(0);
            ListNode  temp=newHead;
     
            while(l1 != null || l2 != null){
                if(l1 != null){
                    carry += l1.val;
                    l1 = l1.next;
                }
     
                if(l2 != null){
                    carry += l2.val;
                    l2 = l2.next;
                }
     
                temp.next = new ListNode(carry%10);
                temp = temp.next;
                carry /= 10;
            }
     
            if(carry==1) 
                temp.next=new ListNode(1);
     
            return newHead.next;
        }
    }

  • 0
    7
    This post is deleted!

Log in to reply
 

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