【剑指offer 面试题7】用两个栈实现队列

时间:2023-03-09 23:16:10
【剑指offer 面试题7】用两个栈实现队列
 #include <iostream>
#include <stack>
using namespace std; template <typename T> class SQueue
{
public:
SQueue():cnt(){}; void push(const T& node);
T pop();
int getSize(); private:
stack<T> pushstack;
stack<T> popstack; int cnt;
}; template <typename T> void SQueue<T>::push(const T& node)
{
pushstack.push(node); cnt++;
} template <typename T> T SQueue<T>::pop()
{
if(popstack.empty())
{
while(!pushstack.empty())
{
T tmp = pushstack.top();
pushstack.pop();
popstack.push(tmp);
}
} if(popstack.empty())
{
throw new exception();
} T ret = popstack.top();
popstack.pop(); cnt--; return ret;
} template <typename T> int SQueue<T>::getSize()
{
return cnt;
} int main()
{
SQueue<int> Queue;
Queue.push();
Queue.push();
Queue.push(); cout<<"currnet size:"<<Queue.getSize()<<endl; cout<<Queue.pop()<<endl; cout<<"currnet size:"<<Queue.getSize()<<endl; cout<<Queue.pop()<<endl;
cout<<Queue.pop()<<endl;
}