gpt4 book ai didi

python - 链表 Python 2.7

转载 作者:行者123 更新时间:2023-11-30 23:45:12 24 4
gpt4 key购买 nike

我在不使用类的情况下尝试实现链接列表时遇到了麻烦(我们的类(class)中还没有实现),并且谷歌根本没有帮助。每个链表示例都使用类,我没有介绍这些类。我可以创建一个链表,在链表的开头添加一个值,但我不知道如何遍历该列表并在特定节点之后添加值。任何帮助,将不胜感激。对我来说最困难的部分是弄清楚如何遍历列表。

def addValue(linkedSet, value):
"""
Adds a new element to a set.
Parameters:
the set to be changed (address of the first node)
the new value to add to the set
Return result: pointer to the head of the modified set. This is
usually the same as the linkedSet parameter, unless the value
added is less than any value already in the set.

If the value is already in the set, return the set unchanged.
This is not an error.
"""
newNode={}
newNode['data']=value
node=linkedSet
if linkedSet==None:
newNode['next']=None
return newNode
if member(linkedSet,value)==True:
return linkedSet
elif linkedSet['next']==None:
newNode['next']=None
linkedSet['next']=newNode
elif linkedSet['next']!=None:
return linkedSet

最佳答案

正如我认为你的 addValue() 函数可能看起来像的一般轮廓......

def addValue(linkedSet, value):

newNode={
'data': value,
'next': None
}

# if linkedSet is None, then you can just return this newNode

# if linkedSet isnt None...
# if linkedSets next is None, then it should just point to this newNode
# (append)

# otherwise, you should set its current next to the next of this newnode,
# and then set its next to this newNode (insert)

这是一个通用的链表。您似乎在建议您的版本是一个更专业的版本,它维护值排序,并且始终期望传递列表的头节点。您需要不断循环每个“下一个”,直到找到一个值大于当前值的值,然后通过移动后续(也可能是前一个)元素的“下一个”引用来插入自身。

关于python - 链表 Python 2.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9689166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com