232.用栈实现队列
栈的特点是先进后出,而队列的特点是先进先出,所以用两个栈,一个先接收元素再将其中元素出栈,压入另一个栈中,即可实现队列
class MyQueue {
public:
stack<int> s_in;
stack<int> s_out;
MyQueue() {
}
void push(int x) {
s_in.push(x);
}
int pop() {
int res;
if(s_out.empty()){
while (!s_in.empty()){
s_out.push(s_in.top());
s_in.pop();
}
}
res=s_out.top();
s_out.pop();
return res;
}
int peek() {
int res= this->pop();
s_out.push(res);
return res;
}
bool empty() {
if(s_out.empty()&&s_in.empty())
return 1;
else
return 0;
}
};
225.用队列实现栈
若和上题一样用两个队列元素进出来实现栈,则会发现由于队列先进先出的特性即使将元素从第一个队列出队再入队到第二个队列,出队顺序仍然是先进先出,未发生改变
所以本题思路为,将第二个队列用作“备份”使用,即pop
时,q1
中仅剩一个元素,其余元素均备份到q2
中,pop
执行结束后,再将其入队到q1
中
class MyStack {
public:
queue<int> q1;
queue<int> q2;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int res;
while (q1.size()>1){
q2.push(q1.front());
q1.pop();
}
res=q1.front();
q1.pop();
while (!q2.empty()){
q1.push(q2.front());
q2.pop();
}
return res;
}
int top() {
int res= this->pop();
q1.push(res);
return res;
}
bool empty() {
if(q1.empty()&&q2.empty())
return 1;
else
return 0;
}
};