Skip to content Skip to sidebar Skip to footer

Python Linked List Minimum Value

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:

Solution 1:

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.

Solution 2:

To iterate over the list you need to update the node variable with the next node on each iteration:

defrearrange(self):
    node = self.head
    ifnot node:
        returnNone# an empty list
    Min = node.value
    while node:
        if node.value < Min:
            Min = node.value
        node = node.next_node    # move onto the next nodereturn Min

Note that this function seems to be poorly named - what is being rearranged?

Post a Comment for "Python Linked List Minimum Value"