有bug版本:
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = ListNode()
# 相加
if (not l1 and not l2):
return None
if not l1:
l1 = ListNode(val = 0)
if not l2:
l2 = ListNode(val = 0)
carry = 0
temp = l1.val + l2.val + carry
if (temp >= 10):
l3.val = temp - 10
carry = 1
else:
l3.val = temp
l3.next = self.addTwoNumbers(l1.next, l2.next)
return l3
此时的carry每轮都会刷新,无法达到真正进位的效果
不如直接把carry值加到下一个结点的值上去(看别人的代码
递归版本:
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = ListNode()
# 相加
if (not l1 and not l2):
return None
if not l1:
l1 = ListNode(val = 0)
if not l2:
l2 = ListNode(val = 0)
temp = l1.val + l2.val
if (temp >= 10):
l3.val = temp - 10 # bug
if (not l1.next):
l1.next = ListNode(val = 0)
l1.next.val += 1
else:
l3.val = temp
l3.next = self.addTwoNumbers(l1.next, l2.next)
return l3
写的过程中还存在很多问题,比如:
- 对于不对称链表没有在进位过程中及时添加新的结点(已解决
- 因为使用递归,所以每轮开始之前都需要判断链表是否为空(已解决
- 不会python的依次循环去链表值,好像这道题只能用递归?(未解决
耗时:1h20min