在链接lis中创建递归函数findValue()

2024-05-14 07:38:11 发布

您现在位置: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不应该是递归调用的参数,因此如果linkedList==None:将为true,因此返回False


Tags: inselfnonenodereturnvaluedefline
2条回答

首先,我想说的是,我不确定这个问题是否属于CS StackExchange——我们更多的是关于数学和理论,而不是关于编码(尽管我确信我们仍然在编码)。我建议您使用StackOverflow或一些面向编程的StackExchange来解决未来的问题

尽管如此,让我们来看看发生了什么。

您有一个节点类,其中包含数据和下一个引用(下一个引用是另一个节点)

节点类也有getter和setter,很好,很好

现在,您似乎在遍历LinkedList时遇到了某种问题—您的findValue()函数似乎调用了非类型对象上的getData—我将假设它相当于Java和其他语言中的null

例如,你知道50根本不在LinkedList中。你调用findValue,它通过你的linkedList递归,然后神秘地中断

切换您的if语句,以便首先进行None检查。如果LinkedList是非类型对象怎么办?然后,检查getData()将失败,因为您正在对没有该属性/方法的对象调用它,而您这样做是因为getData检查在None检查之前。我认为这是问题的根源

但是,用Knuth的话来说——“小心上面代码中的bug;我只是证明了它是正确的,没有尝试过。”

希望这有帮助

这可以通过不同的顺序排列4行来解决。在这些方面:

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

当代码带着linkedList == None到达这里时,它会在检查对象是否为空并返回false之前尝试在空对象中查找.getData()。重新订购这些,您应该可以开始了:

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

相关问题 更多 >

    热门问题