动态队列

Dynamic Queue C++

本文关键字:队列 动态      更新时间:2023-10-16
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中设置QRearNULL是不必要的,因为enqueue在空队列的情况下不使用它。