【问题标题】:retrive function in linked list python在链表python中检索函数
【发布时间】:2020-07-31 09:45:56
【问题描述】:

我是python链表的新手。我在这里做查找功能并获取参数索引并检索该索引上的项目。它在前两个索引中运行良好,但在索引三时 它仍然在索引 2 上返回相同的项目。

class Link:
    class Node:
        def __init__(self,element,_next):
            self.element = element
            self._next = _next

    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, element):
        self.head = self.Node(element,self.head)
        self.size += 1

    def find(self,index):
        if self.isempty():
            raise IsEmptyError("This stack is empty")
        self.cur = self.head
        for x in range(index-1):
            self.cur = self.head._next
        return self.cur

    def retrive(self,index):
        self.curd = self.find(index)
        self.item = self.curd.element
        return self.item

from linkedlist import IsEmptyError
from linkedlist import Link

s = Link()
s.push("one")
s.push("two")
s.push("three")
get1 = s.retrive(1)
get2 = s.retrive(2)
get3 = s.retrive(3)
print(get1,get2,get3)

输出 = 三二二

进程以退出代码 0 结束

它应该得到输出三二一。我的代码有什么问题吗?提前谢谢。

【问题讨论】:

    标签: python data-structures linked-list


    【解决方案1】:

    问题出在您的find() 函数中:

        def find(self,index):
            if self.isempty():
                raise IsEmptyError("This stack is empty")
            self.cur = self.head
            for x in range(index-1):
                self.cur = self.head._next
            return self.cur
    

    特别是 for 循环。对于循环的每次迭代,您只持续调用头部旁边的节点,因为您执行了self.cur = self.head._next。所以,您实际上并没有遍历列表。简单的解决方法是将其更改为 self.cur = self.curr._next,这实际上会前进到链接列表中的下一项

    顺便说一句,最好在 for 循环中将 i 作为迭代器而不是 x,这看起来像 for i in range(index - 1)

    【讨论】:

    • 非常感谢!终于修好了。欣赏!
    猜你喜欢
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 2021-01-25
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2017-11-23
    相关资源
    最近更新 更多