链表-指针

Linked List - pointers

本文关键字:-指针 链表      更新时间:2023-10-16

我创建了一个链表,当我试图打印节点的值并使用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->next变为NULL。也许您应该为列表中的至少一个项目设置ptr->nextNULL?这就是为什么在Cmemset(&object, 0, sizeof(object));中,或者在C++中,具有构造函数是常见的。

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