链接列表Python2.7

2024-09-30 18:20:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在不使用类的情况下尝试实现一个链接列表时遇到了困难(我们在我的课程中还没有实现),而google也没有提供任何帮助。每个链表示例都使用类,我还没有介绍。我可以创建一个链表,在链表的开头添加一个值,但我不知道如何遍历列表并在特定节点后添加值。任何帮助都将不胜感激。对我来说最困难的部分是如何遍历列表。在

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

Tags: ofthetononenode列表newreturn
3条回答

用字典作为链表描述符怎么样? 比如:

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

当需要遍历时,可以从第一个节点开始, 当你需要添加你的结束节点。在

正如我所想的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']

相关问题 更多 >