正在搜索“链表”是否为空

Searching if Linked List is Empty

本文关键字:是否 链表 搜索      更新时间:2023-10-16

所以这与家庭作业有关,但我不会把它放在这里。我真的很想学习c++,但由于某种原因,我在节点维护方面进展缓慢。我的问题与检查链接列表是否为空有关。

我有这个起始代码:

void add_node(node*& head_ptr, const int& payload)
{
 node* my_first_node = new node();
my_first_node->data = payload;
my_first_node->next = nullptr;

}

在头文件中

struct node {
int data;
node* next;
};

我想知道我是应该在添加函数之前做一个while循环,还是作为它的一部分?我有点迷失了摆脱这一部分,但我相信一旦发生,我会得到它。

谢谢!

因此,如果只有头指针,则需要遍历它直到结束节点。

首先,您应该检查head_ptr是否存在。

if (head_ptr == nullptr)
    // assign your first node to the head pointer

否则,您需要到达列表的末尾。既然这是家庭作业,那么一些psuedo代码怎么样。

make a node of interest, call it end_node
while we are not at the end //How can we tell if we are at the end (hint you assign the 
                            // next in your add already check for this)
    move to the next node (interest_node = interest_node->next)
end

现在我们在末端节点,所以您可以在末端添加新节点。

提示(您可能需要检查损坏的链接列表,即循环链接。

我想你需要像这样的东西

head_ptr->next = my_first_node;

在"add_node"函数内部

这将使您的headptr添加一个"真正的"新节点。

对于您的问题(add_node之前的循环)

只是做一些类似的事情

while(head_ptr != nullptr){
... //your code (maybe you can backup the last node in here?)
// write code for head ptr = next node 
}

但请记住,在将"下一个"分配给head_ptr之前,先备份您的"真实"head_ptr。

否则您无法将其取回