My java solution


  • 0
    C
            public class Solution {
             public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	
    	ListNode l3first = new ListNode(0);
    	
    	int count = 0;
    	
        if(l1 == null)
        	return l2;
        else if(l2 == null)
        	return l1;
        
        l3first.val = (l1.val+l2.val)%10;
        count = (l1.val+l2.val)/10;
        
        
        ListNode result = l3first;
        //ListNode l3 = new ListNode(0);
        
        l1=l1.next;
        l2=l2.next;
        
        if(count == 1 || l1!= null || l2 != null)
        {
        	//l3first.next = l3;
        }
        
        while(l1 !=null && l2 != null)
        {
        	ListNode tmp = new ListNode(0);
        	tmp.val = (l1.val+l2.val+count)%10;
        	System.out.println(l3first.val);
        	count = (l1.val+l2.val+count)/10;
        	l1=l1.next;
        	l2=l2.next;
    		
        	l3first.next=tmp;
        	l3first = l3first.next;
        }
        
        while(l1 == null && l2 != null)
        {	ListNode tmp=new ListNode(0);
        	tmp.val = (l2.val+count)%10;
        	count = (l2.val+count)/10;
        	l2=l2.next;
        	l3first.next = tmp;
        	l3first = l3first.next;
        }
        
        while(l2 == null && l1 != null)
        {
        	ListNode tmp = new ListNode(0);
        	tmp.val = (l1.val+count)%10;
        	count = (l1.val+count)/10;
        	l1=l1.next;
        	l3first.next = tmp;
        	l3first=l3first.next;
        }
       if(count == 1)
       {   ListNode tmp = new ListNode(1);
    	   l3first.next = tmp;
       }
     return result;
    }}

Log in to reply
 

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