思路:
class MyStack {
//创建两个队列
queue<int>q1;
queue<int>q2;
public:
MyStack() {}
void push(int x) {
q2.push(x);//插入临时队列
while(!q1.empty())//判断q1是否为空
{
//不为空
q2.push(q1.front());
q1.pop();
}
swap(q1,q2);//交换
}
int pop() {
int x=q1.front();
q1.pop();
return x;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();//只需要判断q1就行了,q2是临时队列,一直为空
//q2是用来过渡的
}
};
解法二:
只用一个队列,在原队列上面改变:
class MyStack {
public:
queue<int>q;
MyStack() {
}
void push(int x) {
int num=q.size();
q.push(x);
for(int i=0;i<num;i++)
{
q.push(q.front());
q.pop();
}
}
int pop() {
int x=q.front();
q.pop();
return x;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};
思路:
如有错误,多多指教