【发布时间】:2012-03-13 17:39:32
【问题描述】:
我在不使用类的情况下尝试实现链接列表时遇到了麻烦(我们的课程中还没有),而谷歌根本没有帮助。每个链表示例都使用了我没有涉及的类。我可以创建一个将值添加到链表开头的链表,但是我不知道如何遍历列表并在特定节点之后添加值。任何帮助,将不胜感激。对我来说最难的部分是弄清楚如何遍历列表。
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上的文档字符串似乎表明后者。 -
你是完全不允许使用类还是对它们不熟悉?
-
使用
var is None和var is not None代替var==None和var!=None -
考虑到课程是学期后期的话题,我怀疑我的教授是否可以使用课程。
-
你的
linkedSet是如何实现的?
标签: python list linked-list