【发布时间】:2017-07-14 00:25:27
【问题描述】:
我了解如何创建没有循环的链表,但我正在努力将常规列表转换为链表。
def addtoHead(theList, value):
#create a new node
node={}
node['data'] = value
node['next'] = theList #connect the new node to the current head
return node #returning the new node as the head of the list
myList=None
myList=addtoHead(myList,7)
myList=addtoHead(myList,9)
myList=addtoHead(myList,10)
def printList(theList):
ptr=theList
while ptr!=None:
print(ptr['data'])
ptr=ptr['next']
现在,我想做同样的事情,除了在循环中,但我很难理解逻辑。
def createList(pythonList):
node={}
head=None
for i in range(len(pythonList)):
node['data'] = pythonList[i]
node['next'] = head
head=pythonList[i]
printList(node)
pythonList=[7,12,14]
createList(pythonList)
我的逻辑是我将数据设置为列表的一个元素,然后将该数据类型连接到头部。然后我将头部重置为数据,然后继续。不幸的是,这打印了 14,然后我得到了错误:
TypeError: 'int' object is not subscriptable
此错误是针对 print(ptr['data'])。我哪里出错了?
【问题讨论】:
-
您意识到每次写信给
node['data']或node['next']时都会覆盖这些值?在调用printList(node)之前尝试print(node),看看它是否符合您的预期。您可能需要重新考虑您的算法。 -
是的,我只是尝试单独打印节点,然后我意识到这是另一个问题
-
在你的for循环头应该等于节点而不是pythonList[i],它是整数
-
直接的问题在于
head=pythonList[i],它指定了int而不是字典作为头部。