You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

2+5=7,4+6=10-10=0(有进位要求),2+5+1=8

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list=new ListNode(0);
ListNode res=list;
int target=0,sum=0;
while(l1!=null&&l2!=null){
sum=l1.val+l2.val+target;
if(sum>9){
sum=sum-10;
target=1;
}else{
target=0;
}

list.next=new ListNode(sum);
l1=l1.next;
l2=l2.next;
list=list.next;
}
while(l1!=null){
sum=l1.val+target;
if(sum>9){
sum=sum-10;
target=1;
}else{
target=0;
}

list.next=new ListNode(sum);
l1=l1.next;
list=list.next;
}
while(l2!=null){
sum=l2.val+target;
if(sum>9){
sum=sum-10;
target=1;
}else{
target=0;
}

list.next=new ListNode(sum);
l2=l2.next;
list=list.next;
}
if (target!=0){
list.next=new ListNode(target);
}
return res.next;
}
}

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
}

python解法类似

class Solution:
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
re = ListNode(0)
r=re
carry=0
while(l1 or l2):
x= l1.val if l1 else 0
y= l2.val if l2 else 0
s=carry+x+y
carry=s//10
r.next=ListNode(s%10)
r=r.next
if(l1!=None):l1=l1.next
if(l2!=None):l2=l2.next
if(carry>0):
r.next=ListNode(1)
return re.next