我为一个学校项目写了几个函数,我让它们工作,但我不明白为什么。它们应该是相同的,但它们只有在一个检查 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;
}
}