Help! what's wrong with my code? Add Two Numbers


  • 0
    M
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         int carry = 0;
         int sum = 0;
         ListNode ln = null;
         while(l1!=null || l2!=null || sum!=0){
             sum += l1 == null?0:l1.val;
             sum += l2 == null?0:l2.val;
             if(sum>=10){
                 carry = 1;
                 sum = sum -10;
             }
             if(ln == null)
                ln = new ListNode(sum);
             else{
                ln.next = new ListNode(sum);
                ln = ln.next;
             }
             if(l1!=null)
                l1 = l1.next;
             if(l2!=null)
                l2 = l2.next;
             
             sum = carry;
             carry = 0;
         }
         ln.next = null;
         return ln;
    }
    

    }


  • 0
    A

    ln has been set to its next and next...
    Before set ln to its next, you must copy its refrence, Then return the copy.

     int carry = 0;
     int sum = 0;
     ListNode ln = null;
     ListNode root = null;
     while(l1!=null || l2!=null || sum!=0){
         sum += l1 == null?0:l1.val;
         sum += l2 == null?0:l2.val;
         if(sum>=10){
             carry = 1;
             sum = sum -10;
         }
         ln.val = sum;
         if(ln == null) {
            ln = new ListNode(sum);
            root = ln;
         }
         else{
            ln.next = new ListNode(sum);
            ln = ln.next;
         }
         if(l1!=null)
            l1 = l1.next;
         if(l2!=null)
            l2 = l2.next;
    
         sum = carry;
         carry = 0;
     }
     ln.next = null;
     return root;

  • 0
    M

    Thank you, I have solved this problem. As you said,I need a refrence targeting at the first of my link list.


Log in to reply
 

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