#include <iostream>
#include <queue>
#include <assert.h>
using namespace std;
template <typename T>
class MyStack
{
public:
void push(T element)
{
if(q1.empty() && q2.empty())
{
q1.push(element);
}
else if(!q1.empty() && q2.empty())
{
q1.push(element);
}
else if(q1.empty() && !q2.empty())
{
q2.push(element);
}
}
void pop()
{
if(!q1.empty())
{
int size=q1.size();
for(int i=0; i<size-1; i++)
{
q2.push(q1.front());
q1.pop();
}
q1.pop();
}
else
{
int size=q2.size();
for(int i=0; i<size-1; i++)
{
q1.push(q2.front());
q2.pop();
}
q2.pop();
}
}
T top()
{
if(!q1.empty())
{
int size=q1.size();
for(int i=0; i<size-1; i++)
{
q2.push(q1.front());
q1.pop();
}
T temp=q1.front();
q1.pop();
q2.push(temp);
return temp;
}
else
{
int size=q2.size();
for(int i=0; i<size-1; i++)
{
q1.push(q2.front());
q2.pop();
}
q2.pop();
T temp=q2.front();
q2.pop();
q1.push(temp);
return temp;
}
}
bool empty()
{
return (q1.empty() && q2.empty());
}
private:
queue<T> q1;
queue<T> q2;
};
void main()
{
MyStack<int> my;
for(int i=0; i<10; i++)
{
my.push(i);
}
while(!my.empty())
{
cout<<my.top()<<" ";
my.pop();
}
cout<<endl;
}
【C++面试题】:用两个队列模拟一个栈
最新推荐文章于 2020-09-24 20:14:55 发布