所以这与家庭作业有关,但我不会把它丢在这里。我真的很想学习 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;
};
我想知道我是否应该在我的 add 函数之前做一个 while 循环,或者作为它的一部分?我有点迷茫,只是把那部分移开,但我相信一旦发生这种情况,我就会得到它。
谢谢!
最佳答案
所以如果你只有头指针那么你需要遍历它直到结束节点。
首先您应该检查 head_ptr
是否存在。
if (head_ptr == nullptr)
// assign your first node to the head pointer
否则你需要到达列表的末尾。由于这是家庭作业,一些伪代码怎么样。
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
现在我们处于末端节点,因此您可以在末端添加新节点。
提示(您可能需要检查损坏的链表,即循环链接。
关于c++ - 搜索链表是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25986045/