我编写了一个程序实现树并首先遍历这个树的广度。该程序包括3个文件:queue.h,tree.h和main.cpp ......这是queue.h
#pragma once
#include <iostream>
template <class T>
struct L1node {
T data;
L1node* next = NULL;
};
template <class T>
class L1queue
{
L1node<T>* pHead, pTail;
public:
L1queue() :pHead(NULL), pTail(NULL) {}
~L1queue() {
if (pHead) {
while (pHead->next) {
L1node<T>* p = pHead;
pHead = pHead->next;
delete p;
}
delete pHead;
}
return 0;
}
bool isEmpty() {
return pHead == NULL:
}
T& head() {
if (isEmpty()) throw - 1;
return pHead->data;
}
void enqueue(T& a) {
L1node<T> p = new L1node<T>(a);
if (isEmpty()) {
pHead = pTail = p;
}
else {
pTail->next = p;
pTail = p;
}
}
void dequeue() {
if (isEmpty()) return;
L1node<T>* p = pHead;
pHead = pHead->next;
delete p;
if (pHead == NULL) pTail = NULL; //Error here
}
};
这是tree.h
#include <iostream>
#include "queue.h"
using namespace std;
class treeNode {
public:
int data;
treeNode* left = NULL;
treeNode* right = NULL;
};
void printLeavesBFT(treeNode* root) {
L1queue<treeNode*> q;
while (!q.isEmpty()) {
treeNode* p = q.head(); cout << p->data << " ";
q.dequeue();
if(p->left) q.enqueue(root->left);
if(p->right) q.enqueue(root->right);
}
}
我遇到了出队功能错误。我不知道原因。你能帮帮我吗?
答案 0 :(得分:2)
pTail
被声明为L1node<T>
,而您打算将其声明为L1node<T>*
。然后,pTail = NULL
毫无意义。
当您编写L1node<T>* pHead, pTail;
时,只有pHead
是指针,pTail
是对象。
替换为
L1node<T> *pHead, *pTail;
或者:
L1node<T>* pHead;
L1node<T>* pTail;