检查链接列表的末尾

Check the end of the linked list

本文关键字:列表 检查链接      更新时间:2023-10-16

我有一个简单的链表结构,我想迭代它。

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;