Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

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:

def min(self):
    node = self.head               #1st element 
    Min = 0                        #node.next_node is the next element
    while node:
        if node.value > node.next_node.value:
            Min = node.next_node.value
        else:
            Min = node.value

i am just comparing the first and the second element. how do i traverse through the entire list

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...