What is wrong with this function to find a maximum value in a linked list?

Hi! Can anyone shed light on why my code to find the maximum value in a linked list does not work? (with import from linked list file)

  current_node = linked_list.get_head_node()
  maximum = current_node.get_value()
  while current_node != None: 
    current_node = current_node.get_next_node()
    if current_node.get_value() > maximum:
      maximum = current_node.get_value()   
    return maximum

Thanks!

If you follow the flow of that loop what are the steps taken, in order?

I would think

  1. Current node goes to current node’s next node
  2. It compares between the new current node’s value and the maximum to see which is bigger, if the new current node’s value is bigger then the maximum will be replaced by that value
  3. As long as the current node is not empty, the loop will repeat. Now taking the new current node’s next node, the new new current node and repeats until there are no more nodes

What about the last step in that loop, return?

It will only return if the while condition is not satisfied?

Edit: Now that you mention it, I do realise that something is a little bit fishy in my chunk of code. I might have mixed up functions and the while loop but I can’t point where exactly went wrong :frowning:

Sorry for a delayed reply, yes I think that may have happened. Remember that return passes the value back to the caller and exits a that point. Should it be a part of the loop? Follow those possible steps and work and out what happens and when.

1 Like