正在搜索“链表”是否为空
Searching if Linked List is Empty
所以这与家庭作业有关,但我不会把它放在这里。我真的很想学习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。
否则您无法将其取回
相关文章:
- 检查注册表项是否链接到(或副本)另一个注册表项
- 我当前实现的双向链表类是否需要重构迭代器 end() 功能?
- 测试双向链表是否形成算术级数
- 是否可以创建带有索引但没有指针的单个链表?
- 给定一个创建的带有货物的链表,我需要使用函数检查实际序列或"train"是否有效
- 如何在用于删除节点的函数中检查我的链表是否C++为空
- 链表的这个别名运算符是否会产生深度复制
- 是否可以将新的列表节点分配给链表的现有节点
- 是否可以从 const 方法迭代链表
- 如何检查链表中的数据是否存在C++
- 不太确定如何从这里继续前进.是否使用链表进行搜索
- 查找链表是否为循环列表
- 如何检查元素是否存在于 c++ 中的链表中
- 对象数组作为链表中的字符数组 - 我对对齐的假设是否有效
- 我的链表实现是否泄漏内存
- 使用链表确定是否合适的子集
- 测试链表是否彼此相等
- 如何检查链表数组中的某个链表是否为空
- 如何使用 c++ 检查链表是否排序
- 需要修改堆栈/链表程序以确定单词是否为回文