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

我没有获得正确的值,并且无法在我的方法中发现问题。

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中的内容和代码,我认为您可以在程序中包含类似此图片的内容,并希望将其打印出来。

c&#43;&#43; - 打印多列表索引-LMLPHP

因此,最重要的是,我将编写类似以下代码的内容:

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

关于c++ - 打印多列表索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32915709/

10-11 22:11
查看更多