迭代链表

时间:2018-02-22 17:17:12

标签: c pointers linked-list

假设我们有

typedef struct Node{
int num;
struct Node *next;
} node;

node *next1 = NULL;
node node1 = {1, &next1};
node *next0 = &node1;
node node0 = {0, &next0};
node *start = &node0;

为什么以下不能迭代它(我们进入无限循环)?

node *p = start;
while (p != NULL){p = p->next; }

3 个答案:

答案 0 :(得分:3)

问题在以下声明中

node node1 = {1, &next1}; /* node1 next field should be next1 not &next1 */

应该是

node node1 = {1, (struct Node*)next1}; /* similarly for node0 */

这是工作代码

#include<stdio.h>
int main() {
        typedef struct Node{
                int num;
                struct Node *next;
        } node;

        node *next1 = NULL;
        node node1 = {1, (struct Node*)next1};
        node *next0 = &node1;
        node node0 = {0, (struct Node*)next0};
        node *start = &node0;

        node *p = start;
        while (p != NULL){
                printf("%d \n",p->num);
                p = p->next;
        }
   }   

答案 1 :(得分:2)

尝试使用此而不是令人困惑的声明。

node node1 = {1, NULL};
node node0 = {0, &node1};
node *start = &node0;

这适合我。

答案 2 :(得分:1)

首先要了解更多有关链接列表的信息。您的列表创建代码完全错误。请阅读以下代码中的我的评论,以了解您的错误: -

Fatal error: Uncaught InvalidArgumentException

您也可以执行以下操作: -

node *node1 = {1, NULL};//or {1,NULL} not the address of pointer, next1 is pointing to NULL, here you have created the first node
//node *next0 = &node1;// what are you doing here and what are you doing below
//node node0 = {0, &next0};//wrong
node node0 = {0, NULL};// here you have created the second node
node *start = &node0;// you have assign the address of second node to start

//you need to join both the nodes to make it a list
start->next = node1; 

现在,下面的代码可以使用。

node *node1 = {1, NULL};//create first node here
node *next0 = {0, node1};//create second node and link to first node already created in above code
node *start = node0;// now start is pointing to the first node of the list