Reputation: 1
I am trying to write a search() function to search a linked list for a node with the requested value and return the node.
Below is my code:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def to_list(self):
out = []
node = self.head
while node:
out.append(node.value)
node = node.next
return out
def search(self, value):
""" Search the linked list for a node with the requested value and return the node. """
# Traverse through the list until a number is found
node = self.head
print(node)
while node != value:
node = node.next
return node
# Test search
linked_list = LinkedList()
linked_list.prepend(2) # Method not shown for brevity
linked_list.prepend(1)
linked_list.append(4) # Method not shown for brevity
linked_list.append(3)
linked_list.to_list()
assert linked_list.search(1).value == 1, f"list contents: {linked_list.to_list()}"
assert linked_list.search(4).value == 4, f"list contents: {linked_list.to_list()}"
Running this code gives me the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-58-d70897699f08> in <module>()
6 linked_list.append(3)
7 linked_list.to_list()
----> 8 assert linked_list.search(1).value == 1, f"list contents: {linked_list.to_list()}"
9 assert linked_list.search(4).value == 4, f"list contents: {linked_list.to_list()}"
<ipython-input-54-c7f29bb4a2be> in search(self, value)
5 print(node)
6 while node != value:
----> 7 node = node.next
8 return node
9
AttributeError: 'NoneType' object has no attribute 'next'
Can anyone point out why I am getting this AttributeError? Had used very similar traversal code in the to_list method so am not sure why I"m encountering this issue in the search method.
Upvotes: 0
Views: 126
Reputation: 148965
The text while node != value
is plain wrong. The node
variable should contain Node
objects or None
. As no node object can be the integer 1 (even if its value attribute could), you end with None
and raise the error.
What you want is:
while node and (node.value != value):
...
Upvotes: 1