创建模板队列时出现问题
Problems creating a Template Queue
我正在尝试编写自己的模板队列类来学习如何使用模板。我看到这种类型的问题经常被问到,我已经阅读了许多回答,但我仍然看不出我做错了什么。
template <class type>
struct Node{
type data;
Node *next;
};
template <class type>
class LinkedListQueue{
public:
LinkedListQueue();
void push(type new_data);
void pop();
type front();
void print();
private:
Node<type> *head;
Node<type> *tail;
};
template <class type>
LinkedListQueue<type>::LinkedListQueue(){
this->head = NULL;
this->tail = NULL;
}
template <class type>
void LinkedListQueue<type>::push(type new_data){
Node<type> *newNode;
newNode->data = new_data;
newNode->next = NULL;
if(this->head == NULL){
this->head = newNode;
this->tail = newNode;
}else{
this->tail->next = newNode;
this->tail = newNode;
}
}
template <class type>
void LinkedListQueue<type>::pop(){
if(this->head != NULL){
this->head = this->head->next;
if(this->head == NULL){
this->tail == NULL;
}
}else{
cout << "Queue is Empty" << endl;
}
}
template <class type>
type LinkedListQueue<type>::front(){
return(this->head->data);
}
int main() {
LinkedListQueue<int> newQueue;
newQueue.push(5);
newQueue.push(4);
cout << newQueue.front() << endl;
newQueue.pop();
cout << newQueue.front() << endl;
}
我无法确定问题出在哪里。如果我注释掉弹出和最后一个前端调用,则第一个 front() 调用会正确输出。然而,取消评论的流行和前面打破了一切。当我尝试调试 pop() 时,列表中似乎只有一个节点。
任何帮助将不胜感激。
您没有分配新节点。 只是存储数据。
Node<type> *newNode; //<=== indeterminate pointer
newNode->data = new_data;
newNode->next = NULL;
不管怎样,你总是在推动一个新元素,所以分配它,设置它,然后弄清楚它的去向。此外,为您的节点创建一个构造函数,该构造函数采用数据的 const-ref,并将 next 设置为 NULL。这使您的代码更加直接(实际上更高效):
Node<type> *newNode = new Node<type>(new_data);
随着节点模板变为:
template <class type>
struct Node
{
Node(const type& value)
: data(value), next(NULL) {};
type data;
Node *next;
};
最后,您的pop()
不是删除节点,只是使用指针。 您可能也想解决这个问题。
template <class type>
void LinkedListQueue<type>::pop()
{
if(this->head != NULL)
{
Node<type>* victim = this->head;
this->head = this->head->next;
if(this->head == NULL)
this->tail == NULL;
delete victim; // <=== note: deleting node.
}
else
{
cout << "Queue is Empty" << endl;
}
}
这是一个大问题:
Node<type> *newNode;
newNode->data = new_data;
声明一个指针并开始直接访问它,而不为其分配内存。这意味着指针指向一个看似随机的位置。导致未定义的行为和奇怪的事情发生是意料之中的。
此外,如果为节点分配内存,则会出现内存泄漏,因为不会释放pop
函数中的节点。
相关文章:
- 在C++中打印对的优先级队列的所有值时出现问题
- 有关如何处理 vulkan 队列系列的问题
- 我有一个问题,创建了C 中阻塞队列的向量
- 关于使用我自己创建的类使用优先级队列的问题
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 我的字符串队列结构有什么问题?
- 队列的同步问题
- 将队列处理为包含文件的文件夹.可能存在的问题
- 使用自定义比较器声明C++优先级队列的问题
- 洗车队列问题
- 语法问题:尝试将节点推送到队列
- 尝试创建队列 - C++崩溃的问题
- 用两个堆栈实现队列——脱队列测试问题
- C++ 我在设置我创建的类的优先级队列时遇到问题
- 将Struct对象推入队列的问题
- Boost库队列的问题
- 我有一个问题,了解如何与队列工作
- 队列的指针问题
- 链表-C++出队问题..出队列重复返回相同的元素
- 对最短路径算法进行建模时的队列问题