美文网首页
C++ 实现队列(链式)

C++ 实现队列(链式)

作者: Jaymz_2b11 | 来源:发表于2020-03-09 19:08 被阅读0次
    #pragma once
    #include "stdio.h"
    namespace SF 
    {
        template<class T>
        struct  QueueNode
        {
            T data;
            QueueNode<T> *next;
    
            QueueNode() 
            {
                this->next = nullptr;
            }
        };
        //链队列
        template<class T>
        class Queue
        {
        public:
            Queue();
            ~Queue();
            void Enqueue(T val);
            QueueNode<T> *Dequeue();
            int Size() { return this->count; };
            void Show();
            void Release() { this->ReleaseQueue(head); };
            bool IsEmtpy() { return this->count > 0; };
        private:
            int count;
            QueueNode<T> *head;
            QueueNode<T> *tail;
            void ReleaseQueue(QueueNode<T> *node);
        };
    
        template<class T>
        Queue<T>::Queue() 
        {
            this->count = 0;
            this->head = new QueueNode<T>();
            this->tail = this->head;
        }
    
        template<class T>
        Queue<T>::~Queue()
        {
            Release();
        }
    
        template<class T>
        void Queue<T>::Enqueue(T val)
        {
            QueueNode<T> *node = new QueueNode <T>();
            node->data = val;
            //尾巴进队
            if (!head->next) 
            {
                head->next = node;
                tail = node;
            }
            else
            {
                tail->next = node;
                tail = node;
            }
            this->count++;
        }
    
        template<class T>
        QueueNode<T>* Queue<T>::Dequeue()
        {
            //头部出队
            QueueNode<T> *node = head->next;
            if (node)
            {
                head->next = node->next;
                this->count--;
            }
            return node;  //这里要返回就不使用delete 了  外部使用完毕需要释放
        }
    
        template<class T>
        void Queue<T>::Show() 
        {
            this->tail = this->head->next;
            while (tail)
            {
                printf("%i\n", tail->data);
                tail = tail->next;
            }
        }
    
        template<class T>
        void Queue<T>::ReleaseQueue(QueueNode<T> *node) 
        {
            if (node) 
            {
                ReleaseQueue(node->next);
                delete node;
            }
        }
    
    
    
    
    
    
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:C++ 实现队列(链式)

          本文链接:https://www.haomeiwen.com/subject/iocmdhtx.html