c++ - 搜索链表是否为空

标签 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;


}

在头文件中加上这个

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/

相关文章:

c - 如何在链表中将节点从头移动到尾? C

c++ - 如何将 WT 小部件放入 PDF?

c++ - DLL 函数从参数获取错误值

c++ - 无法追踪访问冲突 0xC00000FD

c++ - 如何处理 std::find_if() 返回 false?

java - 链表的trim()方法

javascript - 在 html div 中显示所有 DOM 节点

java - 切换链表中的值(处理节点)

javascript - Element.getElementByTag ("mytag")有时返回空

c++ - 无法从 libsupc++ 库中初始化类型为 'std::terminate_handler'(又名 'void (*)()')的变量