python - 在链表中创建递归函数 findValue()

标签 python

我正在尝试创建一个名为 findValue() 的递归函数,用于确定给定的数据值是否在链接列表中。如果该值存在,则该函数返回 True,否则返回 False。这是 Node 类的实现:

class Node:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

这是我到目前为止的代码:

from Node import Node

def findValue(value, linkedList):
    if value == linkedList.getData():
        return True
    if linkedList == None:
        return False
    else:
        print("now:", linkedList.getData())
        print("next", linkedList.getNext())
        return findValue(value, linkedList.getNext())

我尝试使用这些值测试我的代码:

n1 = Node(10); n2 = Node(20); n3 = Node(30); head = Node(40); n2.setNext(n1); 
n3.setNext(n2); head.setNext(n3)

当给定的值不在我的链接列表中时,我希望我的代码返回 False。但是,当我尝试 findValue(50, head) 时,我得到:

now: 40
next: <Node.Node object at 0x10c410ac8>
now: 30
next: <Node.Node object at 0x10bf3b710>
now: 20
next: <Node.Node object at 0x10de5b898>
now: 10
next: None
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    findValue(50, head)
  File "/Users/Shared/Homework3/hw3.py", line 29, in findValue
    return findValue(value, linkedList.getNext())
  File "/Users/Shared/Homework3/hw3.py", line 29, in findValue
    return findValue(value, linkedList.getNext())
  File "/Users/Shared/Homework3/hw3.py", line 29, in findValue
    return findValue(value, linkedList.getNext())
  [Previous line repeated 1 more time]
  File "/Users/Shared/Homework3/hw3.py", line 22, in findValue
    if value == linkedList.getData():
AttributeError: 'NoneType' object has no attribute 'getData'

所以到最后,我看到下一个值是 None。 None 不应该是递归调用的参数,因此 if linkedList == None: 将为 true,从而返回 False?

最佳答案

这可以通过以不同方式排列 4 行来解决。在这些行中:

    if value == linkedList.getData():
        return True
    if linkedList == None:
        return False

当您的代码以 linkedList == None 到达此处时,它会尝试在空对象中查找 .getData(),然后再检查该对象是否为空并返回 false。重新排序这些,你就可以开始了:

    if linkedList == None:
        return False
    if value == linkedList.getData():
        return True

关于python - 在链表中创建递归函数 findValue(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55959141/

相关文章:

python - 根据列表中的项目数对 Python 字典进行排序

python - python 中重叠列表函数在 True 时返回 False

python - Boost.Python 从类型创建句柄

python - Scipy 和 beta 分布 : is is possible to change the range of x values?

python - Scipy - z 值的两个尾部 ppf 函数?

python - 权限错误: [Errno 13] Permission denied | WeasyPrint

python - 如何实现处理 URL 的工作线程队列

python - 如何在python脚本中设置环境变量

python - 逐行执行 Python 脚本

python - 从列表创建数据框