Python Linked list minimum value

家住魔仙堡 提交于 2019-12-13 23:08:48

问题


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


回答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.




回答2:


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

def rearrange(self):
    node = self.head
    if not node:
        return None    # an empty list
    Min = node.value
    while node:
        if node.value < Min:
            Min = node.value
        node = node.next_node    # move onto the next node
    return Min

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



来源:https://stackoverflow.com/questions/30021557/python-linked-list-minimum-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!