簡體   English   中英

從鏈表中獲取最小值?

[英]Get smallest value from a linked list?

我當前正在編寫一段代碼,該代碼循環遍歷鏈接列表並檢索最小的代碼,但無法正常工作。 相反,它似乎正在返回我輸入到列表中的最后一個值...(列表是從main傳遞的頭)

 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 我不知道您為什么要這樣做,但這是錯誤的。 您基本上遍歷了鏈表,還從概念上遍歷了一個數組(根本不存在)。 這是未定義的行為,無法給出有意義的結果。

您必須取消引用當前有效的節點,而不是取消引用位於內存中某個位置之后的幾個索引的數組元素,並通過列表的下一個節點指針前進(我假設這在您的代碼中稱為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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM