我试图打印多链接列表的索引。每个节点有两个元素--一个仓库号和一个工具号。我正在打印每个仓库里的所有工具。我在正确地迭代列表时遇到了问题。
我没有得到正确的值,并且很难在我的方法中找到问题。
struct Node
{
int WarehouseNumber;
int ToolNumber;
struct Node *n;
}
void showWarehouses()
{
int tempvalue;
bool flag = false;
struct Node *s;
s = start;
if (start == NULL)
{
cout<<"Unable";
return;
}
s->WarehouseN = tempvalue;
cout<<"Warehouse "<<tempvalue<< ": Tool ";
while(s != NULL)
{
if (s->WarehouseN == tempvalue)
{
flag = true;
cout<< s->ToolN <<" ";
s = s->next;
}
}
}发布于 2015-10-02 21:12:43
您没有为tempvalue分配任何值,因此它会导致未定义的行为。读取this post.
此外,根据您在struct Node和代码中的内容,我认为您可以在程序中获得类似于这张图片的内容,并希望打印它们。

因此,为了更好地解决这个问题,我将编写类似于以下代码的代码:
void showWarehouses()
{
int tempvalue=1;
bool flag, cont;
struct Node *s;
if (start == NULL)
{
cout << "Unable";
return;
}
cont = true;
while (cont)
{
cont = false, flag = false;
s = start;
while (s)
{
if (s->WarehouseN == tempvalue){
cont = true;
if (!flag){
cout << "Warehouse " << tempvalue << ": Tool ";
flag = true;
}
cout << s->ToolN << " ";
}
s = s->next;
}
cout << endl;
tempvalue++;
}
}发布于 2015-10-02 21:14:59
我假设->warehouseN和->toolN得到相应的仓库和工具名称。这是在你的if声明之后。
struct Node *temp;
while (s != NULL){
temp = s;
cout << "Warehouse " << s->warehouseN << ": Tool ";
while (s!= NULL) {
cout << s->toolN << " ";
s = s-> next;
}
s = temp->next;
cout << endl;
}另外,在将s设置为之前,您可能应该先启动它。
发布于 2015-10-02 21:35:51
如果是这样:
s = start;
struct Node *s;编译后,您在一个更大的范围内有一个s,它在被另一个名为s的变量隐藏在showWarehouses中之前就被设置好了。那会是件坏事。
无论如何,直接的结果是showWarehouses的s从未被初始化过,而且程序没有崩溃可能是一个很糟糕的结果。由于s没有初始化,所以程序的其余部分都在打印垃圾,因此错误的输出是预期的。
https://stackoverflow.com/questions/32915709
复制相似问题