链表-指针
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->next
变为NULL
。也许您应该为列表中的至少一个项目设置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
}
相关文章:
- C++,指针数组,指向双链表中的条目
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 链表指针问题
- 将链表转换为指针数组时出错
- 如何实现容纳整数和无效指针的双向链表?
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 为什么我在空指针错误(链表)中获取成员访问权限
- 链表删除功能的单指针 // 是可能的
- 如何深度复制链表对象指针
- 链表 - 使用后面的指针在末尾插入
- 链表和指针在C++中的点
- 未分配被释放的指针(将堆栈实现为链表时)
- 使用双指针和递归反转链表
- 使用函数引用指向节点的指针删除链表中的节点?
- 使用 XOR 操作仅使用 2 个指针反转链表
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 指针永远不会在链表深层复制构造函数中达到 null
- 链表指针赋值为什么我们不能直接将尾巴分配给 temp 而不是尾巴>尾巴下一个
- 如何从文件读取到动态分配的指向结构的指针链表中?
- C++指针链表