我为一个学校项目写了几个函数,我让它们起作用,但我不明白为什么。它们应该是相同的,但是只有在其中一个检查current-> link并且另一个检查当前自身时,它们才起作用。难道两个循环都不都是当前的!= NULL?
这两个函数在main中的调用方式如下:
customerHead = fillCart(limit, lowLevelInv); //fills linked list
totCart(customerHead, lowLevelInv);
printCart(customerHead, lowLevelInv);
仅当while循环检查当前!= 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;
}
}
最佳答案
看起来问题出在这里:
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不为null,则程序将挂起,因为任何更改都不改变current或current-> link。
如果这实际上不是您的问题(例如,由于复制面食问题),则应向我们展示如何构建列表以及“不起作用”的具体含义。
关于c++ - 为什么一个循环需要链表的current-> link!= NULL和一个current!= NULL?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13595729/