队列以及两个队列实现一个栈
#pragma once template <class T> struct QueueNode { public : QueueNode( const T& x) :_data(x),_next(NULL) {} T _data; QueueNode* _next; }; template <class T> class queue { public : queue() :_head(NULL),_tail(NULL),_size(0) {} ~queue() { QueueNode<T>* begin = _head; while(begin) { QueueNode<T>* tmp = begin; begin = begin->_next ; delete tmp; } } T& GetTop() { T* tmp = (T *)_head; return *tmp; } int GetSize() { return _size; } bool Emptyqueue() { if(_head) return false ; else return true ; } void PushQueue(const T& x) { //空队列 //非空 if(_head == NULL) { _head = new QueueNode<T>(x); _tail = _head; } else { _tail->_next = new QueueNode<T>(x); _tail = _tail->_next ; } _size++; } void PopQueue() { //空 //一个 //两个及以上 if(_head == NULL) { cout<< "该队列为空"<<endl; } else if (_head == _tail) { delete _head; _head = NULL; _tail = NULL; _size--; } else { QueueNode<T>* tmp = _head; _head = _head->_next ; delete tmp; _size--; } } T& operator->() { return *this ; } private : QueueNode<T>* _head; QueueNode<T>* _tail; int _size; }; //两个队列实现一个栈 template <class T> class stack1 { public : void pushstack1(const T& x) { if(!_emptyqueue.Emptyqueue()) { while(!_emptyqueue.Emptyqueue()) { _noemptyqueue.PushQueue (_emptyqueue.GetTop ()); _emptyqueue.PopQueue (); } } _noemptyqueue.PushQueue (x); } void popstack1() { if(_noemptyqueue.Emptyqueue()) { cout<< "该栈为空"<<endl; } while(1) { T tmp = _noemptyqueue.GetTop (); _noemptyqueue.PopQueue (); if(!_noemptyqueue.Emptyqueue ()) { _emptyqueue.PushQueue (tmp); } else break; } } private : queue<T> _emptyqueue; queue<T> _noemptyqueue; };原文链接:https://www.f2er.com/datastructure/382584.html