C++ 打印链表数组C++;

C++ 打印链表数组C++;,c++,arrays,list,printing,C++,Arrays,List,Printing,我不熟悉编码,我正在尝试实现一个链表数组。我已经填充了列表的结构和数组,但是我的print函数只打印数组索引[0],第一个列表元素,而没有将指针移动到数组[0]中的第二个列表元素。本质上,它是一个无限循环,只打印第一个元素 我的问题是:如何将指针移动到列表中的下一个元素,以便我可以完成列表的打印并将数组索引移动到下一个索引 我的结构如下所示: struct Node { int Vertex; Node* next; }; void printList(Node* adjList[5]) {

我不熟悉编码,我正在尝试实现一个链表数组。我已经填充了列表的结构和数组,但是我的print函数只打印数组索引[0],第一个列表元素,而没有将指针移动到数组[0]中的第二个列表元素。本质上,它是一个无限循环,只打印第一个元素

我的问题是:如何将指针移动到列表中的下一个元素,以便我可以完成列表的打印并将数组索引移动到下一个索引

我的结构如下所示:

struct Node
{
int Vertex;
Node* next;
};
void printList(Node* adjList[5])
{
    int a;
    for (int b = 0; b <= 5; b++)
    {
        a = 0;
        while (adjList[a]->next != NULL)
        {
            cout << "(" << adjList[a]->Vertex;
            cout << ", " << adjList[a]->next->Vertex << ") ";
            cout << a << endl;
            system("pause");            
        }
        a++;
    }
    cout << endl << endl;
}
插入所有节点和列表后,我的打印功能如下所示:

struct Node
{
int Vertex;
Node* next;
};
void printList(Node* adjList[5])
{
    int a;
    for (int b = 0; b <= 5; b++)
    {
        a = 0;
        while (adjList[a]->next != NULL)
        {
            cout << "(" << adjList[a]->Vertex;
            cout << ", " << adjList[a]->next->Vertex << ") ";
            cout << a << endl;
            system("pause");            
        }
        a++;
    }
    cout << endl << endl;
}

很难知道您希望打印函数的输出是什么。但是,下面的代码应该输出正确的内容,不会出现崩溃。注意,我通过
printNode
引入了递归,以确保子节点被打印

void printNode(Node* node)
{
    if (node != NULL)
    {
        cout << "(" << node->Vertex;
        cout << ", ";
        printNode( node->next );
        cout << ")";
    }
    else
    {
        cout << "null"; 
    }
}

void printList(Node* adjList[5])
{
    for (size_t index = 0; index < 5; index++)
    {
        printNode(adjList[index]);
        cout << endl; 
    }
}
举例来说,该程序:

int main()
{
    Node *adjList[5];
    adjList[0] = new Node;
    adjList[0]->Vertex = 1;
    adjList[0]->next = new Node;
    adjList[0]->next->Vertex = 4;
    adjList[0]->next->next = NULL; // added, was uninitialized
    adjList[1] = new Node;
    adjList[1]->Vertex = 6;
    adjList[1]->next = new Node;
    adjList[1]->next->Vertex = 7;
    adjList[1]->next->next = NULL; // added, was uninitialized
    adjList[2] = NULL;
    adjList[3] = NULL;
    adjList[4] = NULL;
    printList( adjList );

    return 0;
}
产出:

(1, (4, null))
(6, (7, null))
null
null
null

欢迎来到stackoverlow。请张贴一份MCVE(请参阅),包括main。您的问题可能来自未发布的代码。那么我们就无能为力了。
while(adjList[a]->next!=NULL)
如果条件为真,将以无限循环结束,因为while循环中没有任何东西会改变条件……为什么while循环之后总是将a初始化回0?请在while循环中的最后一行中尝试adjList[a]=adjList[a]->next。您没有遍历列表。我修复了计数器初始化,还添加了您的代码行,它引发了一个读取错误。首先,您的循环应该从[0,5]开始迭代,这意味着循环条件应该是
b<5
not
next;}