返回链表中的最大值

时间:2014-03-31 17:49:21

标签: c++ list

我今天早些时候在这个问题上发了一个问题,但这个问题非常有用,所以我现在提供更多细节。

我试图从链表中返回最大值,但它只返回我输入的第一个值?

结构:

struct Stock{

string itemName;
int itemStock;  //100 crisps etc...
double individualItemCost;
double totalSockValue;
Stock* next;

};

如何调用该函数:

Stock * g = Largest(head, sizeOf);
cout << "Name: " << g->itemName << " Stock: " << g->itemStock << endl;

实际功能:

Stock* Largest(Stock*& list, int size)

{

Stock *current;
current = (list+0);// start_ptr; 
int largestValue = 0;
if (current!=NULL)
{
    while (current->next!=NULL)
    {
        if (current->itemStock < largestValue)
        {
            largestValue = current->itemStock;
            current = current->next; 
        }
        else
        {
            current = current->next; 
        }
    }
}
return current;

}

它返回我输入的第一个值而不是最大值,任何建议都会有所帮助。

这就是我将其读入链接列表的方式,因此您知道:

while (i < sizeOf)
{
    cout << "Please enter the students name: " << endl;
    cin >> head->itemName;
    cout << "Please enter the item stock: " << endl;
    cin >> head->itemStock; 
    cout << "Please enter the item price: " << endl;
    cin >> head->individualItemCost;    

    push(head,head->itemName, head->itemStock, head->individualItemCost);  //Push back everything in head
    i++;

}   

谢谢!

2 个答案:

答案 0 :(得分:1)

你的问题在于:

    if (current->itemStock < largestValue)
    {
        largestValue = current->itemStock;
        current = current->next; 
    }
    else
    {
        current = current->next; 
    }

无论您的代码采用哪个分支,current将始终设置为列表的下一个元素。由于您返回current,您将返回列表的最后一个元素,无论找到的最大值是什么。

我不会用勺子喂你解决方案,但我会给你一个提示:你需要一个类型为Stock*的额外变量,这个变量非常像变量largestValue

答案 1 :(得分:0)

您尝试返回最大值,然后测试值是否更小。您当前的代码如下所示:

if (current->itemStock < largestValue)
{
    largestValue = current->itemStock;
    // (...) 
}

逻辑上等于“来自两个值,选择较小的值并将其设置为最大值”。

最重要的是,如果你只需要这个数字,你就会在整个列表中进行迭代而不记得哪个股票是最大的 - 返回largestValue,而不是current

相关问题