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

时间:2019-05-01 23:49:18

标签: 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?

2 个答案:

答案 0 :(得分:1)

可以通过不同地订购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

答案 1 :(得分:0)

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

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

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

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

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

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

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

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

希望这会有所帮助。