225. 用队列实现栈
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
if (rightQ_.empty()) {
rightQ_.push(x);
}
else {
leftQ_.push(rightQ_.front());
rightQ_.pop();
rightQ_.push(x);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int popElem_ = rightQ_.front();
rightQ_.pop();
while (leftQ_.size() > 1) {
rightQ_.push(leftQ_.front());
leftQ_.pop();
}
if (leftQ_.size()) {
int topElem_ = leftQ_.front();
leftQ_.pop();
while (rightQ_.size()) {
leftQ_.push(rightQ_.front());
rightQ_.pop();
}
rightQ_.push(topElem_);
}
return popElem_;
}
/** Get the top element. */
int top() {
return rightQ_.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return leftQ_.empty() && rightQ_.empty();
}
private:
queue<int> leftQ_;
queue<int> rightQ_;
};
执行结果: