#include#include #include
templateclass Node{ public: T data; //节点内存储的数据. Node * next; //指向下一个节点. template Node(const Ty& data_, Node * n=nullptr); ~Node()=default;};
templatetemplate Node ::Node(const Ty& data_, Node * n) :data(data_) next(n){ //}
templateclass AStack{ //先进后出. private: unsigned int maxSize; //该stack最多能够容纳多少个数据. Node * top; //指向顶部数据的指针. Node * rear; //指向尾部数据的指针. unsigned int counter; //计数,当前stack中有多少个元素. void clear(Node * root)noexcept; //清理该stack中的数据. public: template < std::is_unsigned ::value>::type> AStack(const Ty& size); ~AStack(); template void push(const Ty& value); const Node & top()const noexcept; void pop()noexcept; void clear()noexcept;};
templatetemplate AStack ::AStack(const Ty& size) :maxSize(size), //size top(nullptr), //默认为空。 rear(nullptr), counter(0){ //}
templateAStack ::~AStack(){ this->clear();}
templatevoid AStack ::clear(Node * ptr)noexcept{ if(ptr == nullptr){ return; } if(ptr != nullptr){ this->clear(ptr->next); } delete ptr; ptr = nullptr;}
templateconst Node & AStack ::top()const noexcept //返回当前stack中的第一个数据. { return (this->rear)->data;}
templatevoid AStack ::pop()noexcept //删除当前stack中第一个数据. { Node * headNext = (this->head)->next; delete this->head; this->head = headNext; headNext = nullptr;}
templatevoid AStack ::push(const Ty& value) //压入一条数据进去stack. { if(this->head == nullptr){ ++(this->counter); //this->counter = 1; this->head = new Node (value); this->rear = (this->head)->next; }else{ if(this->counter <= this->maxSize) { this->rear = new Node (value); this->rear = (this->rear)->next; }else{ throw std::runtime_error("Can not bigger than the maxSize!"); } }}
templatevoid AStack ::clear()noexcept{ this->clear(this->head);}