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.
node.nextbecomes none, so you try to accessNone.nextwhich is not possible?self.head = Node(0)rather thanself.head = None. Now all other methods can assume thatself.head.nextrefers to the head (if any) of the list, rather than having to cater toself.headbeing aNodeorNone. The dummy node can be used to store metadata (such as the length) about the list.