首页 > 解决方案 > 如何删除链表中的用户定义节点?

问题描述

此代码应该是一个图书馆管理系统,用户可以在其中从菜单中选择添加书籍、打印添加的书籍列表或删除书籍。我的添加和打印功能有效。但是,我的删除功能没有。添加多本书后,用户可以选择一本书并插入其名称,它将被删除。

为了删除特定的书,我创建了一个新字符串,用户可以输入他们要删除的书的名称。然后我运行了一个遍历节点的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;
    }
    }
}

例如:用户添加一本名为“数学”的书,然后从菜单中选择删除选项,然后用户插入“数学”书,包含该书的节点被删除。

但是每次我测试我得到一个分段错误错误

标签: c++

解决方案


见第一件事。我不明白你为什么在你的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.

如果您不明白任何部分,请注释掉。


推荐阅读