繁体   English   中英

链接列表Python 2.7

[英]Linked Lists Python 2.7

我无法在不使用课程的情况下尝试实现链接列表(在我的课程中我们还没有),谷歌根本没用。 每个链表示例都使用我没有涉及的类。 我可以创建一个链表,在链表的开头添加一个值,但我不知道如何遍历列表并在特定节点后添加值。 任何帮助,将不胜感激。 对我来说最困难的部分是弄清楚如何遍历列表。

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)

这是一般链表。 看起来你建议你的是一个更专业的版本来维护一个值排序,并且总是希望传递列表的头节点。 你需要在每个'next'上不断循环,直到它找到一个值大于当前值的值,然后通过绕过下面(可能是之前的)元素的'next'引用来插入它自己。

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']

如何使用字典作为链表描述符? 就像是:

linkedSet = {'first':firstNode, 'last':lastNode}

然后,当您需要遍历时,您始终可以从第一个节点开始,并且当您需要添加时,您将拥有终端节点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM