Java solution with full comments


  • 1
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            // remain value when sum over 10
            int remain = 0;
            
            // initial result linked list
            ListNode head = null;
            ListNode tail = null;
            
            // loop when we not meet end of l1, l2 or we have remain > 0
            while (l1 != null || l2 != null || remain > 0) {
                // calc sum
                int sum = 0;
                if (l1 != null) {
                    sum += l1.val;
                    l1 = l1.next;
                }
                if (l2 != null) {
                    sum += l2.val;
                    l2 = l2.next;
                }
                
                // sum will plus revious remain value
                sum += remain;
                
                // if sum over 10, remain will be 1
                remain = sum / 10;
                
                // descrease sum value when over 10
                sum %= 10;
                
                // create new node and add to result
                ListNode node = new ListNode(sum);
                if (head == null) {
                    head = tail = node;
                } else {
                    tail.next = node;
                    tail = node;
                }
            }
            
            return head;
        }
    }

Log in to reply
 

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