gpt4 book ai didi

C++链表队列实现和析构函数错误:"Aborted (Core Dumped)"

转载 作者:行者123 更新时间:2023-11-30 02:31:40 25 4
gpt4 key购买 nike

我正在尝试学习 C++,但我在内存管理和析构函数的概念方面遇到了问题。我尝试使用链表编写队列实现,当我尝试在析构函数方法中删除链表节点(粗体)时收到“已中止(核心已转储)”错误消息。如果有人知道我做错了什么,请告诉我!

这是我的析构方法的代码:

template <class T>
Queue<T>::~Queue(){
Node<T> *currHead = head;
while(currHead != NULL){
Node<T> *nextHead = currHead->next;
delete currHead;
currHead = nextHead;
}
Node<T> *currTail = tail;
while(currTail != NULL){
Node<T> *nextTail = currTail->next;
delete currTail;
currTail = nextTail;
}
}

这里是我完整的链表队列实现以供引用:

template <class T>
class Node{
public:
T data;
Node<T> *next=NULL;
};

template <class T>
class Queue{
public:
Queue();
~Queue();
void push(T);
T pop();
int size=0;
Node<T> *head=NULL;
Node<T> *tail=NULL;
};

template <class T>
Queue<T>::Queue(){}

template <class T>
Queue<T>::~Queue(){
Node<T> *currHead = head;
while(currHead != NULL){
Node<T> *nextHead = currHead->next;
delete currHead;
currHead = nextHead;
}
Node<T> *currTail = tail;
while(currTail != NULL){
Node<T> *nextTail = currTail->next;
delete currTail;
currTail = nextTail;
}
}

template <class T>
void Queue<T>::push(T data){
Node<T> *node = new Node<T>;
node->data = data;
if(head == NULL){
head = node;
}else{
tail->next = node;
}
tail = node;
size++;
}

template <class T>
T Queue<T>::pop(){
if(size == 0){
throw "Empty Queue";
}else{
Node<T> *oldHead = head;
T oldData = oldHead->data;
head = head->next;
size--;
delete oldHead;
return oldData;
}
}

编辑:

我也为析构函数尝试了以下定义,但我得到了同样的错误:

template <class T>
Queue<T>::~Queue(){

while(head != NULL){
Node<T> *currHead = head;
head = head->next;
delete currHead;
}

while(tail != NULL){
Node<T> *currTail = tail;
tail = tail->next;
delete currTail;
}
}

最佳答案

在析构函数的第一部分,您要删除从 head 开始的所有列表项。在析构函数的第二部分中,您尝试使用保留在尾部的指针再次删除最后一个列表项,但它已在第一部分中被删除。

关于C++链表队列实现和析构函数错误:"Aborted (Core Dumped)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37403772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com