I am trying to find the minimum value in the list without having to use the min function and just by comparing the first and the next element through the list. This is my attempt:
node = self.head #1st element
Min = 0 #node.next_node is the next element
if node.value > node.next_node.value:
Min = node.next_node.value
Min = node.value
i am just comparing the first and the second element. how do i traverse through the entire list
Best How To :
Answering this specifically would be difficult without knowing the specifics of your node implementation, and as this is almost certainly a homework problem wouldn't be sporting anyway.
What you want to do is go through each element of the list, and compare it to the Min you have. If it's higher, then just go to the next element. If it's lower, then set Min to the value, and go to the next element. There's no need to compare two elements directly: just compare everything to Min. This style of going through a list and doing something with a single value variable is pretty widely useful: you can also use it for things like moving averages.
It's easiest, if not amazingly elegant, to start by setting Min to the value of the first element; that way you'll have something to compare to. If you set it to something else, like 0, then if all your values are higher than 0, you'll never set Min. An alternative is to set Min to something sufficiently large, but that's not as safe as just setting it to the first element's value.
How you loop through the list is dependent on how this list is designed. Something like
while node with
node = node.next_node can work, if a node is always true, and
node.next_node at the end of the list is
None, since this will stop the loop at the end. If you instead raise an error at the end, you'll have to do something else.