我是编程新手,刚刚开始使用python。我最近一直在学习链表,但我在使用函数将项目添加到列表末尾时遇到了问题。下面列出的名为addToTail的函数不起作用,并且给了我错误:TypeError:"NoneType"对象不支持项目分配。任何帮助将不胜感激,谢谢。
def addToHead(myList, value):
node = {}
node['data'] = value
node['next'] = myList
return node
def addToTail(myList, value):
ptr = myList
while ptr != None:
ptr = ptr['next']
node = {}
node['data'] = value
node['next'] = None
ptr['next'] = node
return myList
def printList(myList):
ptr = myList
while ptr != None:
print(ptr['data'])
ptr = ptr['next']
print('None')
def createList(pythonList):
linkedList = None
for i in pythonList:
linkedList = addToHead(linkedList, i)
return linkedList
firstList = createList([5, 10, 15])
addToTail(firstList, 10)
printList(firstList)
您的问题在于addToTail()
函数的这一部分:
ptr = myList
while ptr != None:
ptr = ptr['next']
您实际上是在循环,直到没有下一个节点并且ptr
设置为None
。然后稍后当您尝试为节点分配ptr['next'] = node
时,它显然失败了,因为您尝试访问None
,而不是尾节点。您可以通过在作业之前检查下一项来解决此问题(以保持您的风格(:
ptr = myList
while True:
if ptr['next'] is None:
break
ptr = ptr['next']
问题是你的addToTail
将始终将指针作为None,因为你正在迭代,直到你的值在你的while循环中为none。添加一个指向链表中上一个元素的额外变量 - 这样,您将获得列表中的最后一个值而不是 None。
def addToTail(myList, value):
ptr = myList
prev = ptr
while ptr != None:
prev = ptr
ptr = ptr['next']
node = {}
node['data'] = value
node['next'] = None
prev['next'] = node
return myList