python代码

class Solution(object):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
:author: 凌风技术站-iaccepted
"""
a, b, c = 0, 0, 0
pre = ListNode(-1)
tail = pre

while l1 is not None or l2 is not None:
a = 0
if l1 is not None:
a = l1.val
l1 = l1.next

b = 0
if l2 is not None:
b = l2.val
l2 = l2.next
c += (a + b)
node = ListNode(c % 10)
c //= 10
tail.next = node
tail = tail.next
if c != 0:
node = ListNode(c)
tail.next = node
tail = tail.next
tail.next = None
return pre.next

c++代码

class Solution {
public:
{
ListNode *pre = new ListNode(-1);
ListNode *tail = pre;

int c = 0, sum = 0;
while(l1 != NULL && l2 != NULL)
{
sum = l1->val + l2->val + c;

c = sum / 10;
sum %= 10;
ListNode *node = new ListNode(sum);
tail->next = node;
tail = node;

l1 = l1->next;
l2 = l2->next;
}

ListNode *l = l1;
if (l1 == NULL)l = l2;

while(l != NULL)
{
sum = l->val + c;
c = sum / 10;
sum %= 10;
ListNode *node = new ListNode(sum);
tail->next = node;
tail = node;

l = l->next;
}

if (c != 0)
{
ListNode *node = new ListNode(c);
tail->next = node;
}

return pre->next;
}
};