我无法在不使用课程的情况下尝试实现链接列表(在我的课程中我们还没有),谷歌根本没用。每个链表示例都使用我没有涉及的类。我可以创建一个链表,在链表的开头添加一个值,但我不知道如何遍历列表并在特定节点后添加值。任何帮助,将不胜感激。对我来说最困难的部分是弄清楚如何遍历列表。
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
答案 0 :(得分:2)
就像我认为你的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)
这是一般链表。看起来你建议你的是一个更专业的版本来维护一个值排序,并且总是希望传递列表的头节点。你需要在每个'next'上不断循环,直到它找到一个值大于当前的值,然后通过在下一个(可能是之前的)元素的'next'引用周围移动来插入自己。
答案 1 :(得分:1)
unless the value
added is less than any value already in the set
听起来这个列表应该排序。因此,您浏览列表,找到大于您的值的第一个项目并将其拼接在那里。
通过跟踪当前节点来遍历列表:
def addValue(linkedSet, value):
newNode={}
newNode['data']=value
newNode['next'] = None
#traverse list
current = linkedSet
while True:
if current['value'] == value:
return linkedSet # it was already in that list
if current['value'] > value:
# new node is the new head
newNode['next'] = linkedSet
return newNode # new head
if current['next'] is None:
# new tail
current['next'] = new_node
return linkedSet
if current['next']['value'] > value:
# new node belongs here, splice it in
next_node = current['next']
current['next'] = newNode
newNode['next'] = next_node
return linkedSet
# didnt return so far, try the next element:
current = current['next']
答案 2 :(得分:0)
如何将字典用作链表描述符? 类似的东西:
linkedSet = {'first':firstNode, 'last':lastNode}
然后当你需要遍历时,你总是可以从第一个节点开始, 当你需要添加时,你就拥有了你的终端节点。