一、给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,而且它们的每一个节点只能存储 一位 数字。若是,咱们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您能够假设除了数字 0 以外,这两个数都不会以 0 开头。java
来源:力扣(LeetCode)code
示例:io
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 缘由:342 + 465 = 807
解法:class
分析:咱们使用变量来跟踪进位,并从包含最低有效位的表头开始模拟逐位相加的过程。变量
就至关于你在纸上面计算的和那样,咱们首先从最低有效位也就是列表的 l1 和 l2 的表头开始相加。分析题目给出的数,每位数字都应当处于0-9的范围内,咱们计算两个数字的和时可能会出现“溢出”。例如,5+9=14,这种状况况下,咱们会将当前位置设置为4,并将进位carry = 1带入下一次迭代。进位carry一定是0或者1,由于两个10之内相加的数,绝壁小于20,即便在加上carry,好比 9+9+1 = 19,是不会超过20的。
代码:List
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; int y = (q != null) ? q.val : 0; int sum = carry + x + y; carry = sum / 10; curr.next = new ListNode(sum % 10); curr = curr.next; if (p != null) p = p.next; if (q != null) q = q.next; } if (carry > 0) { curr.next = new ListNode(carry); } return dummyHead.next; } }