python-3.x - 两个数字相加问题(链表) - Python - Leetcode - AttributeError
问题描述
我正在尝试解决这个问题 - 添加两个在Leetcode上的数字
我尝试将两个链表都转换为数组,然后执行添加操作。现在,我正在努力将它们转换回链接列表,这是问题的所需输出。
谁能检查我哪里出错了?我也收到一个属性错误:
AttributeError:“NoneType”对象没有属性“val”
这是我写的代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a = l1 #pointers
b = l2 #pointers
arr1 = []
arr2 = []
while a.next is not None:
arr1.append(a.val)
a = a.next
arr1.append(a.val) #storing the values of linked lists in arrays/lists
while b.next is not None:
arr2.append(b.val)
b = b.next
arr2.append(b.val) #storing the values of linked lists in arrays/lists
rev1 = reversed(arr1) #reversed list
rev2 = reversed(arr2) #reversed list
inta = "".join(str(rev1)) #converting list to strings
intb = "".join(str(rev2))
c = str(inta + intb) #performing addition - the answer we wanted
revc = reversed(c) #answer in string form - reversed (output in string at present)
#trying to convert into linked list and return it
q = l1
for i in revc:
q.val = i
q = q.next
return l1
解决方案
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
head = curr = ListNode()
while l1 and l2:
total = l1.val + l2.val + carry
curr.next = ListNode(total% 10)
carry = total // 10
l1,l2,curr = l1.next, l2.next,curr.next
while l1:
total = l1.val + carry
curr.next = ListNode(total%10)
carry = total // 10
l1, curr = l1.next, curr.next
while l2:
total = l2.val + carry
curr.next = ListNode(total%10)
carry = total//10
l2, curr = l2.next, curr.next
if carry > 0:
curr.next = ListNode(carry)
return head.next
推荐阅读
- python - 类“VideoFileClip”的未解析属性引用“resize”
- python - Beautiful Soup Python findAll 返回空列表
- java - 如果线程池已满时我的线程睡眠时间大于保持活动的秒数,会发生什么情况?
- reactjs - 即使我有一个唯一的键分配给最外层元素,仍然会得到`列表中的每个孩子都应该有一个唯一的“键”道具`
- python - tkinter 文本小部件向我显示:TypeError: get() missing 1 required positional argument: 'index1'
- sql - 找出哪个组的训练组最多
- python - 在 cartopy 地图中嵌入子图
- javascript - 使用它重定向到 html 时,拖放不起作用
- crystal-reports - Crystal Report 公式 IF Then Else 删除小数
- python - 无法打开标签文件。(只有使用MSCOCO才能正常)