python - 合并到链表,但出现不寻常的 None 类型错误
问题描述
合并两个排序的链表并将其作为新的排序列表返回。应该通过将前两个列表的节点拼接在一起来制作新列表。
例子:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
- 我知道这不是最佳解决方案,但我仍然无法理解我的错误。*
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(ListNode):
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
lst =[]
while(l1!=None):
#print("I")
lst.append(l1.val)
l1 = l1.next
while (l2!=None):
#print("I")
lst.append(l2.val)
l2 = l2.next
lst.sort()
#print(lst)
l = ListNode(0)
#temp : ListNode()
temp = l
# temp.val = l.val
for i in lst:
temp.val = i
temp = temp.next
return l
错误是
AttributeError: 'NoneType' object has no attribute 'val'
temp.val = i
解决方案
问题在于下面的行
temp = temp.next
您初始化temp
为,l
但它没有任何下一个元素,它只是一个元素。换句话说temp.next
,None
每当您进行 for 循环的第二次迭代时,您都会看到AttributeError: 'NoneType' object has no attribute 'val'
解决方案:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
lst = [1,2,3,4]
l = ListNode(lst[0])
temp = l
for i in lst[1:]:
temp.next = ListNode(i)
temp = temp.next
推荐阅读
- nativescript - 无法在 nativescript 上安装 nativescript-ffmpeg-plugin
- swift - 在 Swift 中将字符串转换为小端字节?
- javascript - 类组件抛出错误'TypeError:无法解构'this.State'的属性'timerTime',因为它未定义'
- google-cloud-platform - 什么原因导致“Cloud Run 错误:内部系统错误,系统将稍后重试”?故障排除建议?
- python - 2D 平面中任何点(除了自身)的最近邻
- docker - 使用 docker-compose 的 apache pulsar 不工作(/pulsar/conf/standalone.conf(没有这样的文件或目录))
- python-xarray - 如何将横截面数据保存到 netCDF
- javascript - React-beautiful-dnd - 动态待办事项,可以通过表单添加项目
- d3.js - D3轴不正确
- python - 是否可以创建一个控制我的网页的 python 程序?