Linked List: AttributeError

I’m working on implementing the ‘Pointers at different speeds’ exercise.
Linked Lists | Codecademy

from LinkedList import LinkedList # Complete this function: def find_middle(linked_list): fast_node = linked_list.get_head_node() slow_node = linked_list.get_head_node() count = 1 while fast_node: fast_node = fast_node.get_next_node() count += 1 if fast_node.get_next_node(): fast_node = fast_node.get_next_node slow_node = slow_node.get_next_node count += 1 else: if count % 2 == 0: return slow_node.get_next_node().get_value() return slow_node.get_value() def generate_test_linked_list(length): linked_list = LinkedList() for i in range(length, 0, -1): linked_list.insert_beginning(i) return linked_list # Use this to test your code: test_list = generate_test_linked_list(7) print(test_list.stringify_list()) middle_node = find_middle(test_list) print(middle_node.value)

Line 11 keeps giving me the error

File "", line 11, in find_middle
   if fast_node.get_next_node():
AttributeError: 'NoneType' object has no attribute 'get_next_node'

What am I doing wrong?

This error message suggests that you are trying to call the method get_next_node() on an object that is None. In this case, it seems that fast_node is None and therefore does not have a get_next_node() method.

To fix this error, you can check if fast_node is None before calling its method. Here’s an example:
def find_middle(head):
slow_node = head
fast_node = head
while fast_node and fast_node.get_next_node():
slow_node = slow_node.get_next_node()
fast_node = fast_node.get_next_node().get_next_node()
return slow_node

In this version of the code, the while loop condition checks that fast_node is not None and that fast_node.get_next_node() is not None before entering the loop. This should prevent the AttributeError that you were seeing.

hope that helps! :slight_smile:

1 Like