给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
class Solution
{
public ListNode addTwoNumbers(ListNode l1, ListNode l2)
{
boolean carry =false;
ListNode result =new ListNode();
ListNode temp =result;
int sum=0;
while(l1!=null||l2!=null||carry)
{
if(null!=l1)
{
sum = l1.getValue();
l1=l1.getNext();
}
if(null!=l2)
{
sum+=l2.getValue();
l2=l2.getNext();
}
if(carry)
{
sum+=1;
carry=false;
}
if(sum>10)
{
carry=true;
sum-=10;
}
temp.setValue(sum);
ListNode next = new ListNode();
temp.setNext(next);
temp =next;
sum=0;
}
return result;
}
}
class ListNode
{
private int value;
private ListNode next;
public void setNext(ListNode next) {
this.next = next;
}
public ListNode getNext() {
return next;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
标准答案:
class Solution{
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tmp = null;
ListNode result = null;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
carry = sum / 10;
ListNode node = new ListNode(sum % 10);
if (tmp == null) {
tmp = node;
result = tmp;
} else {
tmp.next = node;
tmp = tmp.next;
}
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
}
return result;
}
}