1 问题
使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
2 解法
队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并有变成先进后出的顺序,用两个队列que1和que2实现栈的功能,其中que2其实完全就是一个备份的作用,把que1最后面的元素以外的元素都备份到que2,然后弹出最后面的元素,再把其他元素从que2导回que1,最后清空que2,用于下次备份。
class MyStack {
public:
queue<int> que1;
//用于备份que的数据
queue<int> que2;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
//将que1的元素移动到que2,只保留最后一个队尾的元素
int size = que1.size();
while(--size)
{
//que2依次保存que1的队首元素
que2.push(que1.front());
//que1队首元素依次弹出
que1.pop();
}
//剩余的一个元素即为需要弹出的元素
int res = que1.front();
//弹出队头元素
que1.pop();
//将que2备份的元素给que1
que1 = que2;
//清空que2
while(!que2.empty())
{
que2.pop();
}
return res;
}
/** Get the top element. */
int top() {
int res = this->pop();
//将弹出的队尾元素加回队尾
que1.push(res);
return res;
}
/** Returns whether the stack is empty. */
bool empty() {
return que1.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();
*/