I am working on linked list python code (see code below), and I can't for the life of me work out why when the condition check_value == search_term is clearly True the function does not return that.
https://i.sstatic.net/2hpmp.jpg
You can see that the print statement for the fifth iteration shows that the statement is True, but the function overall evaluates to False. Can anyone explain what I am doing wrong?
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))
Thanks in advance.
Update: Apologies for original post. I wanted to show the output, which is why I included an image. Code is now included.
Thank you for the replies.
You can implement the linked_list_search in a lot simpler way.
def linked_list_search(node, search_term):
# Iterate through list till you reach the tail of the list
while(node):
if(node.value == search_term):
# Return True as soon as you find the search_term
return True
# Assign node to the next node in the list
node = node.next
# Return False if search_term not found in the linked_list
return False