c++ - 动态队列 C++

标签 c++

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/

相关文章:

c++ - for循环中的RSA mpz_powm() : seg fault

c++ - macdeployqt 不复制插件

c++ - 指向任意函数的 "general function signature"指针

c++ - 如何返回指向多维数组的指针?

c++ - 通过命令行以编程方式运行程序

c++ - 如何提高乘法的精度?

c++ - 如何以简单的方式声明可变参数模板类的类型

c++ - Oculus Rift + 点 Sprite + 点大小衰减

c++ - STL或范围算法有效地找到满足谓词的n个连续元素

C++ 程序崩溃。图实现