从链表中获取最小值?

时间:2014-03-31 13:34:20

标签: c++

我目前正在编写一段代码,它循环遍历链表并检索最小的代码但不起作用。相反,它似乎返回我输入列表的最后一个值... (列表是从主要传递的头部)

 int i = 0;
    Stock *node = list;
    int tempSmallest = (list + 0)->itemStock;
    while (node!=NULL)
    {

        if ((list+i)->itemStock < tempSmallest)
        {
            tempSmallest = node->itemStock;         
            node = node->nodeptr;           
        }
        i++;
    }
    return list;

感谢您的任何建议!

2 个答案:

答案 0 :(得分:0)

由于某种原因,您正在取消引用(list+i)并为每个访问过的节点递增i。我不知道你为什么要这样做,但这是错的。您基本上遍历链接列表并且在概念上遍历一个数组(根本不存在)。这是未定义的行为,无法给出有意义的结果。

你必须取消引用当前有效的节点,而不是在RAM中的某个地方之后是几个索引的数组元素,并且通过列表的下一个节点指针前进(我假设这被称为nodeptr in你的代码?)。

像...一样的东西。

Stock *node = list; // hopefully not NULL since I don't check in the next line
int smallest = node->itemStock;

while(node && node = node->nodeptr)
    smallest = std::min(smallest, node->itemStock);

return smallest;

答案 1 :(得分:0)

struct stock{
    stock *next;
    ...
};

这将是您的节点的结构。 然后在初始化它们时,应该将添加的最后一个节点的下一个指针引用到当前添加的节点。 那么代码将是这样的:

stock *node = head; // the head you passed from main
int min = node->price;
for(;node;node=node->next)
{
    if(node->price < min)
        min = node->price;
    if(!node->next)
        break();
}
return min;