链表删除c++中的函数



我试图在c++中完成关于链表的任务,但我的删除功能似乎每次我尝试使用它时都会崩溃。我试过一些不同的东西,但我真的不知道哪里出了问题。例如,如果我在列表中只有一个项目,并试图删除它,它会崩溃,同样适用于任何其他情况。如果有人知道什么是错的,请帮助:)

template <class T>
Error_code List<T>::retrieve(string fn, T& item)
{
if (empty()) return underflow;
Node<T>* temp = head;
while (temp->entry.FlightNO.compare(fn) != 0) {
if (temp->next == NULL)
return not_found;
temp = temp->next;
}
item = temp->entry;
return success;
}
template <class T>
Error_code List<T>::remove(T& item)
{
Node<T>* current = head;
Node<T>* search = new Node<T>(item);
if (head == search) {
head = head->next;
return success;
}
else {
Node<T>* previous = current;
current = current->next;
if (current->next == NULL) {
delete current;
return success;
}
while (current != search)
{
previous = current;
current = current->next;
}
previous->next = current->next;
return success;
}
}

这是我的代码,第一个函数是检索项目并检查它是否确实存在,然后第二个是不工作的remove

评论中提到的一切都是正确的。然而你来这里是为了寻找答案,所以给你:

template <class T>
Error_code List<T>::remove(T& item)
{
Node<T>* current = head;
Node<T>* search = new Node<T>(item); // <--- why?
//if (head == search) {    //<-- always false
//    head = head->next;
//    return success;
//}

Node<T>* previous = current;
current = current->next;
if (current->next == NULL) {
delete current;
return success;
}
while (current != search) // <--- fails here, this is always true (you are comparing pointers, not objects)
{
previous = current;
current = current->next; // <--- because this loop is always true and you have a nullptr terminated list then this will segfault with RAV
}
previous->next = current->next;
return success;
}
}

编辑:只是为了澄清导致段错误的原因,在"循环结束"。最终调用

nullptr->next;

最新更新