Python代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
current = head
carry = 0
while(l1 or l2):
if (l1):
x = l1.val
else:
x = 0
if (l2):
y = l2.val
else:
y = 0
sum = carry+x+y
carry = sum // 10
current.next = ListNode(sum%10)
current = current.next
if(l1!= None): l1 = l1.next
if(l2!= None): l2 = l2.next
if (carry>0):
current.next = ListNode(1)
return head.next
链表的存储,我这里使用了头结点,用于指向链表的第一个元素。