我很确定问题出在 while (!empty()) pop();
上,因为在我将其注释掉之后。一切正常。但它不会delete
head
。这部分有什么问题?
意图如下:LinkedList有两个数据成员,head
和tail
。当列表为空时,它们都应等于 0
。当列表非空时,head
和 tail
都应该是非零的,并且它们应该分别引用列表中的第一项和最后一项。并且应该有一条从 head
到 tail
的路径,通过 next_
指针。如果列表只有一项,则 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;
}
最佳答案
你这里有一部分问题
bool empty() {
return head == 0;
}
什么时候 head
设置为 0
(NULL
)?从来没有?
关于c++ - Stack 析构函数中的双重释放或损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9046495/