Simple Java solution


  • 0
    R
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
           
            if(l1 == null){ return l2;}
            if(l2 == null){ return l1;}
    
            ListNode res = new ListNode(0); 
            ListNode head = res;
            int inc=0;
            int val1,val2;
            while(l1!=null||l2!=null){
               //if l1 &l2 length not match, assume the short one with value 0 to keep traversing the longer list
                if(l1!=null){
                    val1 = l1.val;
                }else{val1 = 0;}
                
                if(l2!=null){
                    val2 = l2.val;
                }else{val2 = 0;}
                
                int val = val1 + val2;
                if(inc == 1){
                    val +=1;
                    inc = 0;
                }
                if(val>=10){
                    inc = 1;
                    val -=10;
                }
               
    
                ListNode node = new ListNode(val);
    			res.next = node;
    			res = res.next;//res is last node in newlist
    			
                if(l1!=null){ l1 = l1.next; }
                if(l2!=null){ l2 = l2.next; }
            }
            if (inc ==1){//there is increment, create a new node with val 1 to the end of list
                ListNode node = new ListNode(1);
                res.next = node;
    			res = res.next;
            }
            return head.next;
        }
    }
    

Log in to reply
 

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