打印多列表的索引

Print Index of a multilist

我正在尝试打印多链表的索引。每个节点都有两个元素——仓库编号和工具编号。我正在打印每个仓库中的所有工具。我在正确遍历列表时遇到问题。

我没有得到正确的值,并且在我的方法中找不到问题。

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;
            }
    }
}

您尚未为 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++;
    }
}

我假设 ->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 before 将其设置为开始

如果这样:

s = start;
struct Node *s;

编译,你有一个范围更广的 s,它在被另一个名为 s 的变量隐藏在 showWarehouses 之前刚刚设置为开始。那将是一件坏事。

无论如何,直接结果是 showWarehousess 从未初始化,程序没有崩溃可能是愚蠢的不幸。由于 s 未初始化,程序的其余部分正在打印垃圾,因此输出错误是可以预料的。