讨论/《中级算法》 - 两数相加/
《中级算法》 - 两数相加
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {;

        ListNode sumList = new ListNode(0), res = sumList;
        int addOne = 0;
        while(l1 != null || l2 != null) {
            int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + addOne;
            addOne = sum > 9 ? 1 : 0;
            ListNode newNode = new ListNode(sum % 10);
            sumList.next = newNode;
            sumList = newNode;

            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }

        if (addOne > 0) {
            ListNode newNode = new ListNode(1);
            sumList.next = newNode;          
        }

        return res.next;

    }
}
展开全部 4 讨论