我之前想的太简单,以为两个链表的长度相同,所以对应元素直接相加就可以了,
要考虑的情况是:1.两个链表长度不一样 2.尾部如果有进位,要多加一个节点
///欠考虑的做法
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy=ListNode(0)
current = dummy
sums=0
carry=0
while l1 or l2:
sums=l1.val+l2.val
val=sums%10+carry
carry=sums/10
l1=l1.next
l2=l2.next
current.next=ListNode(val)
current=current.next;
return dummy.next
///考虑周全的写法
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
current, carry = dummy, 0
while l1 or l2:
val = carry
if l1:
val += l1.val
l1 = l1.next
if l2:
val += l2.val
l2 = l2.next
carry, val = val / 10, val % 10
current.next = ListNode(val)
current = current.next
if carry == 1:
current.next = ListNode(1)
return dummy.next