c++ - 如何删除链表中的用户定义节点?
问题描述
此代码应该是一个图书馆管理系统,用户可以在其中从菜单中选择添加书籍、打印添加的书籍列表或删除书籍。我的添加和打印功能有效。但是,我的删除功能没有。添加多本书后,用户可以选择一本书并插入其名称,它将被删除。
为了删除特定的书,我创建了一个新字符串,用户可以输入他们要删除的书的名称。然后我运行了一个遍历节点的while循环,直到找到该书名存在于哪个节点并将其删除。
// 书籍信息的结构体
struct Book
{
string Name;
string Author;
string Publisher;
string Year;
string ISBN;
Book *next;
};
// delete function
void deleteBook (Book * &, Book * &)
{
if (head == NULL) // condition when no books are added
{
cout << " Empty List" << endl;
}
else if (head == last) // if one book is added
{
delete head;
head = NULL;
last = NULL;
}
else
{
cout << "Please Enter The Name of The Book You Wish to Delete: " <<
endl;
string n;
cin >> n;
while (last->Name != n) // to delete a specific book
{
Book *temp = new Book;
temp = last;
last=last->next;
delete temp;
}
}
}
例如:用户添加一本名为“数学”的书,然后从菜单中选择删除选项,然后用户插入“数学”书,包含该书的节点被删除。
但是每次我测试我得到一个分段错误错误
解决方案
见第一件事。我不明白你为什么在你的while循环中使用last。您应该使用 head(temp) 来搜索 name is the list 。这里为了简单起见,我假设 struct 只有两个成员的书名和下一个指针。
Book *temp = head;
//Check base condition by yourself
while(temp->next->name != Name && temp->next != NULL) // this will go until we reach 1 one node before the main node which you need.Suppose your book is at 5th position it'll stop at 4th.
Book *temp2 = temp->next; // it will point to the node you want to delete ie temp2 is 5th node and temp is 4th nod.
// Now just do linking
temp->next = temp2->next; // in 4th's next store 5th's next
delete(temp2); //assuming you are in c++ or use free() if in C.
如果您不明白任何部分,请注释掉。
推荐阅读
- javascript - 谁是 JS(对象或函数)中的最父实体?
- json - 我无法从 json_decode() 数组中读取值
- node.js - 来自 rabbitmq /publish 的神秘“响应代码 400(错误请求)”消息
- elasticsearch - 在 ElasticSearch 中重新索引与更新 Api
- c# - ASP.NET Core 3.1 登录重定向问题
- node.js - 如何在 ejs 模板中访问 req.session 值
- github - 是否有一个稳定的 url 可以始终在 github 中获取默认分支?
- java - ViewPager Cache 使 SearchView 结果看起来很奇怪
- c# - 客户端卡住下载网站源c#
- java - 如何检查whatsapp号码java android