本题是关于用两个栈实现了队列的基本功能:push,pop,peek和empty。在两个栈里面,stIn用于存储push操作添加的元素,stOut用于存储pop和peek操作弹出的元素。关键点在于理清在pop和peek元素时,如果stOut中没元素,会先将stIn的元素压到stOut中,再从stOut中pop,这样顺序就和队列一致。
思路:
- push函数将元素x直接压入stIn。
- pop函数返回队列的第一个元素,即stOut栈的栈顶元素,并弹出该元素。如果stOut为空,要先将stIn中的所有元素导入stOut中,以便将元素按照队列的顺序弹出。
- peek函数返回队列的第一个元素,即stOut栈的栈顶元素,但不会弹出该元素。这个功能可以直接调用已有的pop函数来获取stOut的栈顶元素,然后再将该元素重新push进stOut中。
- empty函数判断队列是否为空,如果stIn和stOut两个栈都为空,则返回true,否则返回false。
代码:
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while (!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
int result = this->pop(); // 直接使用已有的pop函数
stOut.push(result); // 因为pop函数弹出了元素result,所以再添加回去
return result;
}
bool empty() {
return stIn.empty() && stOut.empty(); // 当两个栈都为空时才返回true
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/