繁体   English   中英

链表-指针

[英]Linked List - pointers

我创建了一个链表,当我尝试打印节点的值并使用NULL作为绑定时,它不起作用。 例如:

#include <iostream>

typedef struct Node;
typedef Node* Node_ptr;
struct Node
{
    int i;
    Node_ptr next;
};

int main()
{
    Node_ptr ptr, head;
    ptr = new Node;
    head = ptr;

    // load
    for(int j = 0; j < 4; j++)
    {
        ptr->next = new Node;
        ptr->i = j;
        ptr = ptr->next;
    }

    // print
    ptr = head;
    while(ptr->next != NULL)
    {
        std::cout << "print: " << ptr->i << std::endl;
        ptr = ptr->next;
    }
}

但是,当我运行此代码时,代码陷入while循环的无限循环中。 它永远不会理解链表只有5个节点,它一直在继续。 我不明白为什么会这样。

您可能只需要初始化指针(为NULL),否则它们将只包含垃圾,因此也将显示为有效指针。

例如:

for(j = 0; j < 4; j++)
{
   ptr->next = new Node;
   (ptr->next)->next = NULL;
   ptr->i = j;
   ptr = ptr->next;
}

尝试值初始化您的Node

ptr = new Node();

代替

ptr = new Node;

否则,您只会在成员中有垃圾。

while(ptr->next != NULL)

您清楚地对其进行了编码,直到ptr->nextNULL为止。 也许您应该为列表中的至少一项将ptr->next设置为NULL 这就是为什么在C普遍使用memset(&object, 0, sizeof(object)); ,或在C++中具有构造函数。

typedef struct Node
{
  int i;
  Node* next;
  Node() : i(0), next(NULL) {} //prevents this problem
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM