232.用栈实现队列
https://leetcode.cn/problems/implement-queue-using-stacks/
用两个栈实现队列
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int res = stOut.top();
stOut.pop();
return res;
}
int peek() {
int res = this->pop();
stOut.push(res);
return res;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
225. 用队列实现栈
https://leetcode.cn/problems/implement-stack-using-queues/
用一个队列实现栈
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
size --;
while(size--){
q.push(q.front());
q.pop();
}
int res = q.front();
q.pop();
return res;
}
int top() {
return q.back();
}
bool empty() {
return q.empty();
}
};