题目描述
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的标准操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入:
[“MyStack”, “push”, “push”, “top”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
解题
队列的特性是先入先出
栈的特性时先入后出
实际上,一个队列就能解决问题了。
当元素出栈时,需要最后一个进来的元素出去,但是队列中会让第一个进来的元素出去,所以需要把最后一个元素之前的所有元素全都执行出队列再进队列操作,然后让最后一个元素出队列就行了
代码
class MyStack {
public:
queue<int>myQueue;
MyStack() {
}
void push(int x) {
myQueue.push(x);
}
int pop() {
int count=myQueue.size();
while(count>1){
myQueue.push(myQueue.front());
myQueue.pop();
count--;
}
int re=myQueue.front();
myQueue.pop();
return re;
}
int top() {
int count=myQueue.size();
while(count>1){
myQueue.push(myQueue.front());
myQueue.pop();
count--;
}
int re=myQueue.front();
myQueue.push(myQueue.front());
myQueue.pop();
return re;
}
bool empty() {
return myQueue.empty();
}
};