我正在处理链表 python 代码(请参阅下面的代码),但我终其一生都无法弄清楚为什么当条件 check_value == search_term 显然为 True 时,该函数不返回那个。
https://i.stack.imgur.com/2hpmp.jpg
您可以看到第五次迭代的打印语句显示该语句为 True,但函数整体评估为 False。谁能解释一下我做错了什么?
class LinkedListNode:
def __init__(self,value,next_node = None):
self.value = value
self.next_node = next_node
def linked_list_search(node,search_term):
check_value = node.value
next_node = node.next_node
if not next_node == None:
next_node_value = next_node.value
if check_value == search_term:
return True
else:
linked_list_search(node.next_node,search_term)
if check_value == search_term:
return True
return False
#Below are lines of code that create a linked list,#and then search for two values in that linked list:
#one that is there,one that isn't. If your function
#works,it should print True then False.
node_7 = LinkedListNode(5)
node_6 = LinkedListNode(2,node_7)
node_5 = LinkedListNode(9,node_6)
node_4 = LinkedListNode(1,node_5)
node_3 = LinkedListNode(4,node_4)
node_2 = LinkedListNode(6,node_3)
root_node = LinkedListNode(7,node_2)
print(linked_list_search(root_node,9))
print(linked_list_search(root_node,3))
提前致谢。
更新:对原帖表示歉意。我想显示输出,这就是我包含图像的原因。现在包含代码。
感谢您的回复。