题目描述
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
Java代码1
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p1 = l1;
ListNode p2 = l2;
ListNode ans = new ListNode();
ListNode temp = ans;
int out = 0;
int sum = 0;
while(p1 != null && p2 != null) {
sum = p1.val + p2.val + out;
temp.val = sum % 10;
out = sum / 10;
p1 = p1.next;
p2 = p2.next;
if(p1 != null || p2 != null || out != 0) {
temp.next = new ListNode();
temp = temp.next;
}
}
if(p1 != null) {
while(p1 != null) {
sum = p1.val + out;
temp.val = sum % 10;
out = sum / 10;
p1 = p1.next;
if(p1 != null || out != 0) {
temp.next = new ListNode();
temp = temp.next;
}
}
}
if(p2 != null) {
while(p2 != null) {
sum = p2.val + out;
temp.val = sum % 10;
out = sum / 10;
p2 = p2.next;
if(p2 != null || out != 0) {
temp.next = new ListNode();
temp = temp.next;
}
}
}
if(out != 0) {
temp.val = out;
}
return ans;
}
}
Java代码2
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode(0);
ListNode cursor = root;
int carry = 0;
while(l1 != null || l2 != null || carry != 0) {
int l1val = l1 != null ? l1.val : 0;
int l2val = l2 != null ? l2.val : 0;
int sumval = l1val + l2val + carry;
carry = sumval / 10;
ListNode sumNode = new ListNode(sumval % 10);
cursor.next = sumNode;
cursor = sumNode;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
return root.next;
}
}