2016-11-20 75 views
-2

我是新来的编码,我试图实现一个链接列表数组。我有结构和列表数组填充,但我的打印功能只打印数组索引[0],第一个列表元素,而不移动指针到数组[0]中的第二个列表元素。实质上,它是一个无限循环,只能打印第一个元素。打印链接列表数组C++

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

我的结构是这样的:

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

忽略的部分,我打印出“一”然后暂停,因为我试图找出我遇到的另一个问题。但现在我想我需要的是如何将指针移动到每个数组索引处列表中的下一个元素。

编辑:阅读下面的评论后,这里是我的主要与列表阵列的一小部分的产生:

int main() 
{ 
    Node *adjList[5]; 
    adjList[0] = new Node; 
    adjList[0]->Vertex = 1; 
    adjList[0]->next = new Node; 
    adjList[0]->next->Vertex = 4; 
    adjList[1] = new Node; 

    ... 

    printList(adjList); 
+0

欢迎stackoverlow。请发布一个MCVE(请参阅http://stackoverflow.com/help/mcve),其中包括main。您的问题可能来自您未发布的代码。然后,我们无法帮助。 – jpo38

+0

'while(adjList [a] - > next!= NULL)'如果条件为真,将会以无限循环结束,因为while循环中没有任何内容会改变条件... – jpo38

+0

为什么while循环后总是初始化为0?在while循环内的最后一行尝试adjList [a] = adjList [a] - > next。你没有遍历列表。 –

回答

0

很难知道你期待什么输出打印功能。但是,下面的代码应该输出正确的东西,不会崩溃。请注意,我通过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; 
    } 
} 

您必须确保未使用next属性被设置为NULL,这样的递归可以停止。所以,你的初始化必须是:

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

通过实例,这个程序:

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