0

我为一个学校项目写了几个函数,我让它们工作,但我不明白为什么。它们应该是相同的,但它们只有在一个检查 current->link 而另一个检查 current 本身时才有效。两个循环都不应该是当前的!= NULL吗?

这两个函数在 main 中调用,如下所示:

customerHead = fillCart(limit, lowLevelInv); //fills linked list
totCart(customerHead, lowLevelInv);                 
printCart(customerHead, lowLevelInv);

仅当 while 循环检查 current != NULL 时才有效

int totCart(OrderPtr head, inventory lowLevelInv[])
{
OrderPtr current;
current = head;
int tot = 0;

while(current != NULL)
{
    tot += lowLevelInv[current->itemID].cost*current->qtyReceived;
    current = current->link;
}
cout<<"Cart total is: "<<tot<<endl;
return tot;
}

这个只有在 while 循环检查 current->link !=NULL 时才有效

void printCart(OrderPtr head, inventory lowLevelInv[])
{
OrderPtr current;
current = head;

cout<<"you have ordered: \n";

while(current->link != NULL);
{
    cout<<current->orderID<<": "<<current->qtyReceived<<" "    <<lowLevelInv[current->itemID].name<<" for "<<lowLevelInv[current->itemID].cost*current->qtyReceived<<endl;
    current = current->link;
} 
}
4

1 回答 1

2

看起来问题在这里:

while(current->link != NULL);
{
    cout<<current->orderID<<": "<<current->qtyReceived<<" "    <<lowLevelInv[current->itemID].name<<" for "<<lowLevelInv[current->itemID].cost*current->qtyReceived<<endl;
    current = current->link;
} 

如果你仔细看,你会在“while”语句中的控制语句后面有一个虚假的分号。这意味着如果 current->link 不为空,您的程序将挂起,因为不会更改 current->link 或 current->link。

如果这实际上不是您的问题(例如,由于复制面食问题),您应该向我们展示您是如何构建您的列表的,以及“不起作用”的具体含义。

于 2012-11-28T00:44:10.733 回答