leetcode 232 用栈实现队列
思路
- 使用两个栈,一个用于输入,一个用于输出;
- 弹出输入栈的全部元素到输出栈,输出输出栈时,为队列顺序
- Tips: 为确保输入顺序,当输出栈空后,输入栈一次性全部出完;此时才能保证有序;
题解
class MyQueue {
public:
stack<int> st1;
stack<int> st2;
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
if(st2.empty()) {
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
}
int res = st2.top();
st2.pop();
return res;
}
int peek() {
if(st2.empty()) {
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
}
int res = st2.top();
return res;
}
bool empty() {
return st1.empty() && st2.empty();
}
};