Simple Java solution


  • 1
    S
     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int c = 0;
            ListNode res = null;
            ListNode head = null;
            
            while(l1 != null || l2 != null || c != 0) {
                
                int l1Val = l1 == null ? 0 : l1.val;
                int l2Val = l2 == null ? 0 : l2.val;
                
                int sum = l1Val+l2Val;
                int cur = (sum+c)%10;
                c = (sum+c)/10;
                
                if(res != null) {
                    res.next = new ListNode(cur);
                    res = res.next;
                }else {
                    res = new ListNode(cur);
                    head = res;
                }
                if(l1 != null) l1 = l1.next;
                if(l2 != null) l2 = l2.next;
            }
            
            return head;
        }

Log in to reply
 

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