1. 问题
2. 解决办法
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
"""
dummy_head = ListNode(0)
current, carry = dummy_head, 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 = divmod(val, 10)
current.next = ListNode(val)
current = current.next
if carry == 1:
current.next = ListNode(1)
return dummy_head.next
s = Solution()
l1 = ListNode(2)
l12 = ListNode(4)
l13 = ListNode(3)
l1.next = l12
l12.next = l13
l2 = ListNode(5)
l22 = ListNode(6)
l23 = ListNode(4)
l2.next = l22
l22.next = l23
a = s.addTwoNumbers(l1, l2)
print(a.val)
print(a.next.next.val)
3. 解决思路:
代码中非常巧妙的点:
用了一个为0的伪链表头,这样在指定next的时候很好地解决了问题;
把问题回归到最简单的数值加法中去,用一个变量来记录是否进位
判断的简介性
考虑周全:如果最大仍然有进位?
来自:https://leetcode.com/problems/add-two-numbers/solution/
4. 个人记录:
竟然花了很多时间在想怎么创建链表,测试时候才能正确输出,后来发现,LeetCode内部已经帮你写好了一部分,你只需要定义你所需要负责的这一部分就好了,链表的定义,调用类,比对预期输出和实际输出,这些都已经在LeetCode内部写好了。
也就是,不需要注释的那一堆,也会判断为正确,accepted.
相反,如果你不注释掉内部提前内衣好的链表的类,会提示错误:
Line 92: Exception: Type <class '__main__.ListNode'>: Not implemented