这个队列类的出列方法不能正常工作,我不知道为什么。当我运行它时,它说" *错误在./a.out' ;:双重免费或损坏(fasttop):0x00000000018dfe50 * ",然后是回溯和然后"中止(核心倾销)"。
起初我直接删除了底部节点,但我认为这可能是问题所以我改用另一种方式删除它们。
以下是出列方法:
int Queue::dequeue() {
if (isEmpty()) {
cout << "ERROR: Can't dequeue from empty Queue"<< endl;
return -1;
} else {
Node* n = top;
if (n == NULL){
bottom = top;
return 0;
}
if (n->next == NULL){
delete n;
bottom = top;
return 0;
}
while(n->next->next != NULL){
n = n->next;
}
bottom = n;
n = n->next;
delete n;
return 0;
}
}
以下是整个文件:
#include <iostream>
using namespace std;
struct Node {
int data;
Node *next;
};
class Queue {
public:
Queue(); //constructor
~Queue(); //destructor
void enqueue(int d); //enqueues node onto top of Queue
int dequeue(); //dequeues bottom node off of Queue -- returns integer dequeued
bool isEmpty(); //checks if Queue is empty
void print(); //print contents of Queue from top to bottom
private:
Node* top; //points to top node in Queue
Node* bottom; //points to bottom node in Queue
};
Queue::Queue() {
top = NULL;
bottom = NULL;
}
Queue::~Queue() {
while (!isEmpty())
dequeue();
}
void Queue::enqueue(int d) {
Node* temp = new Node;
temp->data = d;
temp->next = top;
top = temp;
if (temp->next == NULL){
delete bottom;
bottom = temp;
}
}
int Queue::dequeue() {
if (isEmpty()) {
cout << "ERROR: Can't dequeue from empty Queue"<< endl;
return -1; //error
} else {
Node* n = top;
if (n == NULL){
bottom = top;
return 0;
}
if (n->next == NULL){
delete n;
bottom = top;
return 0;
}
while(n->next->next != NULL){
n = n->next;
}
bottom = n;
n = n->next;
delete n;
return 0;
}
}
bool Queue::isEmpty() {
return (top==NULL);
}
//Print Queue from top to bottom
void Queue::print(){
Node* n = top;
while(n != NULL){
cout << n->data << endl;
n = n->next;
}
cout << endl;
}
int main(){
Queue* s = new Queue();
s->print();
s->enqueue(20);
s->enqueue(30);
s->print();
s->enqueue(40);
s->enqueue(12);
s->print();
s->dequeue();
s->print();
s->dequeue();
s->print();
s->dequeue();
delete s;
return 0;
}
答案 0 :(得分:1)
每当删除节点时,都需要更新指向要删除的节点的所有指针。你需要在两个地方做到这一点。
首先,在n->next == NULL
案例中,Queue
只有一个节点。致电delete n
后,top
仍然指向此已删除的节点,您需要在更改{{1}的值之前更新top
(更改为NULL或nullptr
) }}
在最后一种情况下,如果列表中有多个节点,则删除最后一个节点,但前一节点的bottom
指针仍然指向它。在next
表达式之后,您需要将n = n->next
设置为指向bottom->next
现在指向的节点(因为n->next
是{{1}中的最后一个节点},是NULL)。