来源:LeetCode第二题
# 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
"""
if self.getLength(l1) < self.getLength(l2): #保证l1永远比l2更长
l1, l2 = l2, l1
head = l1
while(l2):#执行加法
l1.val += l2.val
l1 = l1.next
l2 = l2.next
p = head
while(p):#处理进位
if p.val > 9:
p.val -= 10
if p.next:
p.next.val += 1
else:
p.next = ListNode(1)
p = p.next
return head
def getLength(self, l):#计算链表长度
length = 0
while(l):
length += 1
l = l.next
return length
T = Solution()
print(T.addTwoNumbers([1,8,9,6],[9,8,7]))
报错:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [4], in <cell line: 44>()
42 T = Solution()
43 #T.getLength()
---> 44 print(T.addTwoNumbers([1,8,9,6],[9,8,7]))
Input In [4], in Solution.addTwoNumbers(self, l1, l2)
8 def addTwoNumbers(self, l1, l2):
9 """
10 :type l1: ListNode
11 :type l2: ListNode
12 :rtype: ListNode
13 """
---> 14 if self.getLength(l1) < self.getLength(l2): #保证l1永远比l2更长
15 l1, l2 = l2, l1
17 head = l1
Input In [4], in Solution.getLength(self, l)
38 while(l):
39 length += 1
---> 40 l = l.next
41 return length
AttributeError: 'list' object has no attribute 'next'
刚刚练习LeetCode第二题的时候,代码一直上面这个错误,请问一下友友们应该怎么解决啊?