LeetCode-两数相加

输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)

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;
}
}