从链表中获取最小值
Get smallest value from a linked list?
我目前正在编写一段代码,该代码循环遍历链表并检索最小的代码,但不起作用。相反,它似乎返回了我在列表中输入的最后一个值......(列表是从主服务器传递的头部)
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;
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用递归的数组的最小值.这是怎么回事
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- txt 文件中浮点数的最大和最小值
- 余数运算符的等效操作,用于处理低于允许的最小值
- 如何获取进程内存的最小值和最大值?(C++)
- 获取最大值、平均值和最小值
- 如何获取队列的最小值和最大值
- 如何更好地使用 STL 和函子来获取滑动窗口最小值的解决方案
- 获取 2D 数组中数字的平均、最小值和最大值
- 从向量向量中的列中获取最小值和最大值
- 如何获取向量中的最大值或最小值
- 数组类-获取最大值和最小值
- 从2个无符号整数中获取最小值
- 从链表中获取最小值