链表析构函数中的分段错误

Segmentation fault in LinkedList destructor

本文关键字:分段 错误 析构函数 链表      更新时间:2023-10-16
LinkedList::~LinkedList()
{
    Node *ptr = head;
    while (ptr->getNext() != nullptr) {
        Node *hold = ptr;
        ptr = ptr->getNext();
        delete hold;
    }
}

在实例化空的 LinkedList 对象时,我在 while 循环的条件下遇到分段错误。我还将在下面添加 Node 和 LinkedList 类 cpp 文件。

链接列表.cpp

#include "LinkedList.h"
LinkedList::LinkedList()
{
    head = nullptr;
}
/** Make sure to dereference Node pointer when returning **/
Node* LinkedList::getNode(int e) {
    Node *ptr = head;
    while (ptr->getNext()) {
        if (ptr->getExponent() == e) {
            return ptr;
        }
        ptr = ptr->getNext();
    }
    return nullptr;
}
void LinkedList::addNode(int c, string b, int e) {
    Node *n = nullptr;
    *n = Node(c, b, e);
    if (!head) {
        head = n;
        return;
    }
    else if (n->getExponent() < n->getExponent()) {
        n->setNext(head);
        head = n;
    }
    else {
        Node *ptr = head;
        while (ptr->getNext()) {
            if (ptr->getNext()->getExponent() > n->getExponent()) {
                n->setNext(ptr->getNext());
                ptr->setNext(n);
                return;
            }
            ptr = ptr->getNext();
        }
        ptr->setNext(n);
    }
}
void LinkedList::deleteNode(int e) {
    if (!head) {
        return;
    }
    else if (head->getExponent() == e) {
        Node *hold = head;
        head = head->getNext();
        delete hold;
    }
    else {
        Node *ptr = head;
        while (ptr->getNext()) {
            if (ptr->getNext()->getExponent() == e) {
                Node *hold = ptr->getNext();
                ptr->setNext(ptr->getNext()->getNext());
                delete hold;
                return;
            }
            ptr = ptr->getNext();
        }
    }
}
string LinkedList::toString() {
    string line = "";
    Node *ptr = head;
    while (ptr->getNext()) {
        line += ptr->getTerm() + "";
        ptr = ptr->getNext();
    }
    return line;
}
void LinkedList::derive() {
}
LinkedList::~LinkedList()
{
    Node *ptr = head;
    while (ptr->getNext() != nullptr) {
        Node *hold = ptr;
        ptr = ptr->getNext();
        delete hold;
    }
}

节点.cpp

#include "Node.h"
#include <string>
#include <sstream>
using namespace std;
Node::Node() {
    coefficient = 0;
    base = "";
    exponent = 0;
    next = nullptr;
}
Node::Node(int c, string b, int e) {
    coefficient = c;
    base = b;
    exponent = e;
    next = nullptr;
}
string Node::getTerm() {
    stringstream term;
    term << coefficient << base << "^" << exponent;
    return term.str();;
}
Node::~Node() {}

是的,我知道这不是你这样做的方式,我可能会给你一个错误的建议,但是,如果你把:

~Node() { delete getNext(); }
~LinkedList () { delete head; }

然后是一个函数从列表中选取一个特定的节点,并为前一个节点提供对下一个节点的引用,那么你就不必做所有复杂的事情,比如取消引用nullptr。

/!\ 在这种情况下,当然,您必须设置要删除的节点:

node_you_want_to_remove->next=nullptr;

(阅读下面的评论以获取进一步说明(

好吧,这只是我的意见,如果我错了,我很乐意解释原因。

祝你今天开心。