c++ - 在 C++ 中的有序链表中插入一个新节点
问题描述
我正在使用 c++ 在 Visual Studio 中编写一些代码,它是一个有序链表,但我在使用指针时遇到了一些麻烦。
我有三种不同的方法/功能来执行这项任务。
/*
* insert_head: Insert a node at the beginning of the list.
*/
book *inserta_head(book *head, book *newNode){
newNode->next = head;
return newNode;
}
/*
* insert_after: Insert a new node after another one.
*/
void insert_after(book *node, book *newNode){
newNode->next = node->next;
node->next = newNode;
}
/*
* insert: Adds a new node (ordered by code) to the list.
*/
void insert(book* head, int code, char name[40], char lastName[40], char title[40], int year, int lend) {
book* newNode = crear_libro(code, name, lastName, title, year, lend);
book* aux = head;
// If the list is empty.
if (head == NULL){
head = insert_head(head, newNode);
} else {
// If the new node goes before the head.
if (aux->code > newNode->code){
head = insert_head(head,newNode);
} else {
while (aux != nullptr && aux->code < newNode->code)
aux = aux->next;
// Verify the code isn't repeated
if (aux != nullptr && aux->code == newNode->code){
printf("Error: Verify the code. \n");
} else {
insert_after(aux,newNode);
}
}
}
}
我试过运行代码。每次我尝试打印列表时,它都会说它是空的。我检查了我的打印方法和创建节点的方法,它们都在工作,所以我很确定它与指针有关,但我找不到错误。
解决方案
您的insert
函数会更改head
指针。但是该指针是您调用该函数的头指针的副本。所以insert
函数外的头指针是不变的。这就是为什么没有任何东西被添加到列表中。
一个简单的解决方法是使head
参数成为参考。
void insert(book*& head, int code, ...
推荐阅读
- javascript - 如何使用httpClient从角度访问可观察对象的数据?
- asp.net-core - NET Core 3 应用程序中的 Kubernetes 服务发现 404
- cookies - @hapi/bell (discord) --> @hapi/cookie 身份验证切换
- sql - 添加条件以仅返回空值
- android - Android Studio 空闲时 CPU 使用率为 20%
- symfony - 如何在学说查询生成器中使用 orWhere inside andWhere
- java - 如何在 JavaFX 中向 ComboBox 添加掩码?
- python - 可靠的大容量数据流的最佳方法:带有 Django 通道的 websockets?
- python - 在给定列中填充上方单元格中的值
- spyne - get_object_as_xml 不适用于多态性