私はそれがコメントアウトした後、問題がwhile (!empty()) pop();
にあると確信しています。すべて正常に動作します。それはdelete
head
ではありません。この部分に何が問題なのですか?スタックのデストラクタでダブルフリーまたは破損
次のとおりです。LinkedListには、head
とtail
という2つのデータメンバーがあります。リストが空の場合、これらは両方とも0
に等しくなければなりません。リストが空でない場合、head
とtail
は両方とも0でなく、それぞれリストの最初と最後の項目を参照する必要があります。そしてnext_
ポインターを経由してhead
からtail
までのパスが存在しなければならない。リストに項目が1つしかない場合は、head == tail
。
#include <iostream>
//stack using linked list
class LinkedList {
public:
LinkedList() : head(0), tail(0) {}
~LinkedList() {
while (!empty()) pop();
std::cout<< "~LinkedList" << std::endl;
}
void pop() {
node* temp;
temp = head;
for (; temp->next_ != 0; temp = temp->next_) {
tail = temp;
}
delete temp;
tail->next_ = 0;
std::cout << "pop()" << std::endl;
} //removes, but does not return, the top element
int top() {
return tail->value_;
} //returns, but does not remove, the top element
bool empty() {
return head == 0;
}
void push(const int& value) {
node* element = new node(value);
if (empty()) {
head = tail = element;
} else {
tail->next_ = element;
tail = element;
}
} //place a new top element
private:
class node {
public:
node(const int& input) : value_(input), next_(0) {};
int value_; //store value
node* next_; //link to the next element
};
node* head;
node* tail;
};
int main() {
LinkedList list;
list.push(1);
list.push(2);
std::cout << list.top() << std::endl;
list.pop();
std::cout << list.top() << std::endl;
return 0;
}
は、次のコードにデストラクタを変更することで、問題を修正:あなたの場合
~LinkedList() {
while (head != tail) pop();
delete head;
std::cout<< "~LinkedList" << std::endl;
}
ちょうど注 - 単一のリンクされたリストを使用している場合は、スタックの先頭を末尾ではなく先頭に保つのが簡単で効率的です。 –
'pop'関数は決して' head'を変更しませんが、 'empty'関数は' head'だけをチェックします。何かそこに間違いがあります。 – Mat
@Mat最終的に、 'tail'と' head'はその場所を指し、 'delete temp'は' head'を解放するのですか? – ihm