在c++中的链表末尾插入一个节点(walter/savitch)
Inserting a node at the end of a linked list in c++ (walter/savitch)
此函数用于在尾部节点后插入一个节点。这只是我们书中的一个练习题,我很难解决。data()和link()函数分别用于检索节点的信息和下一个指针。编译器在这一行给我一个错误:cursor->set_link(i);
void list_tail_insert(node* head_ptr, const node::value_type& entry)
{
assert (head_ptr != NULL);
const node *temp = head_ptr;
const node *cursor;
node *i = new node; // this is the new tail pointer
i->set_data(entry);
i->set_link(NULL);
if (!head_ptr) // if the linked list is empty
{
head_ptr = i; // the tail pointer is the new head pointer
}
for (cursor = head_ptr; cursor != NULL; cursor = cursor -> link())
{
cout << "Iterating to the tail pointer" << endl;
}
cursor->set_link(i);
}
您有两个问题。
第一个是:
if (!head_ptr) // if the linked list is empty
{
head_ptr = i; // the tail pointer is the new head pointer
}
在这里,您分配给head_ptr
变量,但由于变量是通过值传递的,这意味着它们被复制,因此您只更改变量的本地副本。从调用方传递给函数的变量不会更改。要使其工作,您必须通过引用传递头指针:
void list_tail_insert(node*& head_ptr, const node::value_type& entry)
第二个问题是,在循环之后,变量cursor
将是NULL
。循环条件应该是例如cursor->link() != NULL
。
最终工作代码:
void list_tail_insert(node* head_ptr, const node::value_type& entry)
{
assert (head_ptr != NULL);
node *cursor;
node *i = new node; // this is the new tail pointer
i->set_data(entry);
i->set_link(NULL);
if (!head_ptr) // if the linked list is empty
{
head_ptr = i; // the tail pointer is the new head pointer
}
for (cursor = head_ptr; (cursor -> link()) != NULL; cursor = cursor -> link())
{
cout << "Iterating to the tail pointer" << endl;
}
cursor->set_link(i);
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '