描述
两数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路
两个链表同时移动,谁先到达空,谁不移动,移动非空的,注意进位(step),当链表都移动到空的时候,如果step不为0,需要人为加一个节点值为1.
代码
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//固定头节点,一般头节点是不存储的,但是这个题目头节点需要存储
ListNode node = null;
//每次开始移动的节点
ListNode first = null;
//每次新建的节点,写在外面减少内存消耗
ListNode temp = null;
//res:a+b的结果,step:进位
int a = 0, b = 0, res = 0, step = 0;
while (l1 != null || l2 != null) {
if (l1 == null) {
a = 0;
} else {
a = l1.val;
}
if (l2 == null) {
b = 0;
} else {
b = l2.val;
}
res = a + b + step;
if (res >= 10) {
res = res % 10;
step = 1;
} else {
step = 0;
}
temp = new ListNode(res);
if (first == null) {
first = temp;
node = first;
} else {
first.next = temp;
first = first.next;
}
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (step != 0) {
first.next = new ListNode(step);
}
return node;
}