为什么一个循环需要电流>链接 !=NULL 和一个电流 != NULL 作为我的链表?

Why does one loop require current->link !=NULL and one current != NULL for my linked list?

本文关键字:NULL 一个 链表 我的 循环 为什么 gt 链接      更新时间:2023-10-16

我为一个学校项目写了几个函数,我让它们工作,但我不明白为什么。 它们应该是相同的,但只有当一个检查当前>链路而另一个检查当前本身时,它们才有效。两个循环不应该都是当前的!= 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 循环检查当前>链路时有效!=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"语句的控制语句后面有一个虚假的分号。这意味着如果当前>链接不为空,您的程序将挂起,因为没有任何内容会更改当前或当前>链接。

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

相关文章: