//Reference: http://www.programcreek.com/2012/12/add-two-numbers/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/*
题意是将两个链表相加 但这两个链表是反序存储的 (每个节点只包含一位数字)
要求返回相加后的链表 大于10 要进位 还是保留1位数字
注意 Input 5
5
Output [0,1]
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null)//如果
return l2;
if(l2==null)
return l1;
int carry=0;
ListNode newHead=new ListNode(-1);
ListNode l3=newHead;
while(l1!=null||l2!=null){
if(l1!=null){
carry+=l1.val;
l1=l1.next;
}
if(l2!=null){
carry+=l2.val;
l2=l2.next;
}
l3.next=new ListNode(carry%10);
carry=carry/10;
l3=l3.next;
}
if(carry==1)//如果carry/10=1 如5+5 则结果为 0 ,1
l3.next=new ListNode(1);
return newHead.next;
}
}