template<class T>
class QueueD: public IQueue<T>{
private:
Node<T> *QFront, *QRear;
public:
QueueD(): QFront(NULL), QRear(NULL){}
bool empty()const{
return QFront==NULL;
}
bool enqueue(const T &info){
Node<T> *p=new Node<T>(info,NULL);
if(QFront==NULL)
QFront=p;
else
QRear->setNext(p);
QRear=p;
return true;
}
bool dequeue(T &info){
if (empty()) return false;
else{
info=QFront->getInfo();
Node<T> *p=QFront;
if(QRear==QFront)
QRear=NULL;
QFront=QFront->getNext();
delete p;
return true;
}
}
};
template<class T>
class Node{
private:
T info;
Node *next;
public:
Node(const T &c, Node *p): info(c), next(p){
}
Node *getNext()const{
return next;
}
void setNext(Node *p){
next=p;
}
T &getInfo(){
return info;
}
};
我一直在努力更好地理解 C++,我想知道你们是否可以向我解释几行我在这里不理解的代码。
QFront=QFront->getNext();
QFront 如何知道下一个节点是哪个?在代码中,它只为 QRear 设置。
if(QRear==QFront) {QRear=NULL;}
为什么这是必要的?
编辑:添加节点模板
最佳答案
当队列为空时 QFront == QRear
,因此当您为 QRear
设置下一个元素时,您也将有效地为 QFront 设置下一个元素。这就是 QFront 知道下一个元素的方式。
我认为在 dequeue
中将 QRear
设置为 NULL
是不必要的,因为它不会在 enqueue
中使用,以防万一空队列。
关于c++ - 动态队列 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24598843/