从链表中获取最小值

Get smallest value from a linked list?

本文关键字:最小值 获取 链表      更新时间:2023-10-16

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

 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;

感谢您的任何建议!

由于

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

您必须取消引用当前有效的节点,而不是在 RAM 中的某个位置后面有几个索引的数组元素,并通过列表的下一个节点指针前进(我假设这在您的代码中称为 nodeptr

像...

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;
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;