检查链接列表的末尾
Check the end of the linked list
我有一个简单的链表结构,我想迭代它。
struct Node{
int data;
struct Node *next;
};
假设我创建了一个数据为1的节点,而没有初始化next
。
Node* test3 = new Node;
test3->data = 1;
由于next不是NULL
,所以当我迭代这个链表时,我不能设置限制条件
我认为没有任何方法可以检测内存是否已分配
我该如何解决这个问题?
在使用C++时,也可以向结构中添加构造函数。这更安全,因为你不能忘记初始化下一个指针:
struct Node{
int data;
struct Node *next;
Node() : next(0) {}
};
创建new Node
时,next
会自动初始化为NULL
==0。
正如您所猜测的,next
成员不能用于确定这一点,因为它具有未定义的值,并且任何从中读取的尝试都是未定义的行为。您需要设置它,或者确保它已设置。如果不能做到这一点,则需要通过其他方式跟踪最后一个节点,例如将指向最后一个结点的指针存储在变量中。
这是最愚蠢的问题。。。。或者,如果你不熟悉链表。
每次创建new
时,只需初始化next = 0;
即可
然后,您可以设置一个if
条件,检查您正在处理的节点是否有下一行或最后一行。
类似于:
node* test = new node;
test->data = 1;
test->next = 0;
//[....]
test = test->next;
if (test)
{
//do what you have to...
}
如果if
条件失败,则前一个节点是最后一个节点
您也可以将其设置为:
if (test->next) //next != 0
{
//this is not the last node
}
else //next = 0
{
//this is the last node
}
编辑2015_11_26-0154
node* test = new node;
test->initialized = 0;
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 包含链接列表的链接列表给出了堆的损坏错误:原因
- C 链接列表创建链接列表的链接列表
- 检查链接列表中的重复项
- 标准模板库列表 - 双重链接或循环链接
- 正在检查链接列表(C++)中的用户输入
- 检查链接列表的末尾
- Qt -用预处理器指令检查链接的.lib在windows上的可用性