【问题标题】:Trouble Understanding Linked Lists in Python难以理解 Python 中的链表
【发布时间】: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而不是字典作为头部。

标签: python list typeerror


【解决方案1】:

需要稍作改动。您需要在循环中声明一个新节点inside

def createList(pythonList):
    head = None
    for i in pythonList:
        new_node = {}
        new_node['data'] = i
        new_node['next'] = head
        head = new_node

在循环结束时,将 head 分配给创建的新节点。在下一次迭代中,下一个新节点将引用 head。

目前,您所做的不是更改 head 正确指向的引用(在第一次迭代后将其指向一个整数),从而产生该错误。

在循环之外,运行:

printList(head)    
print(head)

它看起来像这样:

14
12
7
{'data': 14, 'next': {'data': 12, 'next': {'data': 7, 'next': None}}}

这正是您的 sans 循环代码所做的。

【讨论】:

  • 感谢您的精彩解释!我现在明白了:)
  • @sneakysnake 很高兴为您提供帮助!
【解决方案2】:

因此,您需要在代码中进行 2 处更正。
1.你需要为每个循环创建新节点
2. head 应该是你创建的新节点。

def printList(theList):
    ptr=theList
    while ptr!=None:
        print(ptr['data'])
        ptr=ptr['next']

def createList(pythonList):
    head=None
    for i in range(len(pythonList)):
        node={}
        node['data'] = pythonList[i]
        node['next'] = head
        head = node
    printList(node)

pythonList=[7,12,14]
createList(pythonList)  

结果将是

14  
12  
7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多