LeetCode 232 Implement Queue using Stacks
概述
https://leetcode.com/problems/implement-queue-using-stacks/
双栈法
class MyQueue {
public:
stack<int>* a;
stack<int>* b;
MyQueue() {
this->a = new stack<int>;
this->b = new stack<int>;
}
void push(int x) {
a->push(x);
}
int pop() {
return popOrPeek(true);
}
int peek() {
return popOrPeek(false);
}
bool empty() {
return a->empty() && b->empty();
}
int popOrPeek(bool isPop) {
if (b->empty()) {
while (!a->empty()) {
b->push(a->top());
a->pop();
}
}
int top = b->top();
if (isPop) b->pop();
return top;
}
};