题目
使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
思路
- 栈是先进后出,队列是先进先出。当pop()操作时把最后进的元素弹出。所以当我们用队列的时候,模拟pop()操作需要把队列的元素弹出直到得到最后一个数字,前面弹出的数字需要用另一个队列保存。
- 准备两个队列q1和q2。
- push:
- 先检查q1和q2哪个队列不为空,把push的元素放到不为空的那个队列中。
- 因为push进来的元素肯定是最新的元素,即栈里面的top元素,所以设置一个变量topVal来保存这个元素。
- pop:
- pop操作需要把最后进的元素丢弃掉,所以把非空的队列的元素逐个出队列再进入另一个队列。
- 当倒数第二个元素出队列的时候,它将为弹出最后一个元素之后的top值,所以更新topVal。
- 当最后一个元素出队列的时候,不让它进另一个队列,这样就完成了pop()操作。
- top():返回topVal的值。
- empty(): 看两个队列是否都为空。
代码
class MyStack {
private:
queue<int> q1, q2; // 两个队列配合工作
int topVal; // 保存栈顶值
public:
/** Initialize your data structure here. */
MyStack() {
topVal = 0;
}
/** Push element x onto stack. */
void push(int x) {
topVal = x;
if ( q1.empty() ) // 每次只有一个队列不为空。
q2.push( x );
else
q1.push( x );
return;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int temp = 0;
if ( q1.empty() ) { // 如果q1为空,说明元素都在q2中。
while ( !q2.empty() ) { // q2的元素逐个出队列。
temp = q2.front();
q2.pop();
if ( q2.size() == 1 ) // 如果q2中只剩一个值,则上一个出队列的元素将为之后栈的顶点元素。
topVal = temp;
if ( !q2.empty() ) // 如果队列为空,则说明最后一个元素已经出队列,此时这个应该被pop出去的元素不进q1。
q1.push( temp );
}
}
else {
while ( !q1.empty() ) {
temp = q1.front();
q1.pop();
if ( q1.size() == 1 )
topVal = temp;
if ( !q1.empty() )
q2.push( temp );
}
}
return temp;
}
/** Get the top element. */
int top() {
return topVal;
}
/** Returns whether the stack is empty. */
bool empty() {
return q1.empty() && q2.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/