C++ 正在搜索链接列表是否为空
这和家庭作业有关,但我不会把它扔在这里。我真的想学习C++,我只是因为某些原因在节点维护上做得很慢。我的问题是检查链接列表是否为空 我有以下开始代码:C++ 正在搜索链接列表是否为空,c++,nodes,C++,Nodes,这和家庭作业有关,但我不会把它扔在这里。我真的想学习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; } 在头文件中
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;
};
我想知道我是应该在add函数之前做一个while循环,还是作为它的一部分?我有点迷茫,只是把这部分的方式,但我相信我会得到它一旦发生
谢谢 因此,如果只有头指针,则需要遍历它直到结束节点 首先,您应该检查
头\u 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;
内置“添加节点”功能
这将使您的头部添加一个“真正的”新节点
对于您的问题(在添加_节点之前循环)
只是做一些像
while(head_ptr != nullptr){
... //your code (maybe you can backup the last node in here?)
// write code for head ptr = next node
}
但记住,在为头部ptr分配“下一步”之前,备份“真实”头部ptr
否则您无法将其取回。是否应该将
添加_node()
添加到链接列表的末尾?@DalyFrank没问题。