1题目
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
-
void push(int x) 将元素 x 压入栈顶。
-
int pop() 移除并返回栈顶元素。
-
int top() 返回栈顶元素。
-
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
2链接
视频:队列的基本操作! | LeetCode:225. 用队列实现栈_哔哩哔哩_bilibili
3解题思路
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
4代码
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size--;//为了留住队列中的最后一个元素,即栈中要弹出的第一个元素
while (size--) {
que.push(que.front()); //获取到队列中的第一个元素是什么,然后在队尾加入这个元素
que.pop(); //弹出队列中的第一个元素,注意是复制第一个元素值到队尾,不是直接移动
}
int result = que.front();
que.pop();
return result;
}
int top() {
return que.back();
}
bool empty() {
return que.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();
*/