public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pHead = new ListNode(0);
ListNode p = pHead;
int val1;
int val2;
int carry = 0;
while(l1!=null||l2!=null){
if(l1 !=null){
val1 = l1.val;
l1=l1.next;
}else{
val1 = 0;
}
if(l2 !=null){
val2 = l2.val;
l2=l2.next;
}else{
val2 = 0;
}
int data = (val1+val2+carry)%10;
carry = (val1+val2+carry)/10;
p.next = new ListNode(data);
p = p.next;
}
if(carry == 1){
p.next = new ListNode(1);
}
return pHead.next;
}
}
比较重要的代码是 data = (val1+val2+carry)%10 carry = (val1+val2+carry)/10