Jos*_*osh 1 c++ struct pointers linked-list nodes
我创建了一个链表,当我尝试打印节点的值并使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此代码时,代码会陷入while循环中的无限循环中.它永远不会理解链表只有5个节点长,它只是继续前进.我不明白为什么会这样.
您可能只需要初始化指针(为NULL),否则它们只会包含垃圾,因此也会显示为有效指针.
例如:
for(j = 0; j < 4; j++)
{
ptr->next = new Node;
(ptr->next)->next = NULL;
ptr->i = j;
ptr = ptr->next;
}
Run Code Online (Sandbox Code Playgroud)