LinkedList析构函数中的分段错误

时间:2015-11-17 00:55:20

标签: c++ linked-list

LinkedList::~LinkedList()
{
    Node *ptr = head;
    while (ptr->getNext() != nullptr) {
        Node *hold = ptr;
        ptr = ptr->getNext();
        delete hold;
    }
}

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

LinkedList.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;
    }
}

Node.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() {}

1 个答案:

答案 0 :(得分:0)

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

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

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

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

node_you_want_to_remove->next=nullptr;

(阅读以下评论以获得进一步说明)

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

祝你有个美好的一天。