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

约翰

我试图创建一个名为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?

本尼·普罗潘

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

话虽如此,让我们看看发生了什么。

您有一个具有数据和下一个引用的Node类(下一个引用是另一个Node)。

您也可以使用Node类的getter和setter方法,很好。

现在您似乎在遍历LinkedList时遇到了一些问题-您的findValue()函数似乎在NoneType对象上调用了getData-我将假定它与nullJava和其他语言等效

因此,对于您的示例,您知道LinkedList中根本没有50。您调用findValue,它通过您的linkedList递归,然后神秘地中断...

切换您的if语句,因此“无”检查首先出现。如果LinkedList是NoneType对象怎么办?然后,检查getData()将会失败,因为您是在没有该属性/方法的对象上调用它的-之所以这样做,是因为getData检查先于None检查。我认为这是问题的根源。

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

希望这可以帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章