题目介绍
请你仅使用两个队列实现一个后入先出(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提示:
1 <= x <= 9 最多调用100 次 push、pop、top 和 empty 每次调用 pop 和 top 都保证栈不为空
进阶:你能否实现每种操作的均摊时间复杂度为 O(1) 的栈?换句话说,执行 n 个操作的总时间复杂度 O(n)
,尽管其中某个操作可能需要比其他操作更长的时间。你可以使用两个以上的队列。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目解析
栈的数据结构为先进后出,后进先出
队列数据结构为先进先出,后进后出
两者的数据结构顺序相反,想要使用队列实现栈的功能,则需要对队列存储的数据结构进行反序操作,这个反序操作可以在两个时候执行,也就是push或者pop的时候。
在Push时进行反序存储,也就是队列的顶部为最后一个添加的元素
时间复杂度:入栈操作O(n),其余操作都是 O(1)
空间复杂度:O(n),其中 n 是栈内的元素。需要使用两个队列存储栈内的元素。
在pop时进行反序删除,定义队列元素为n,也就是把前n-1个元素依次执行pop、push,把最后一个元素pop掉
时间复杂度:入栈操作 O(n),其余操作都是 O(1)。
空间复杂度:O(n),其中 n 是栈内的元素。需要使用一个队列存储栈内的元素。
下面用第一种思路演示一下
class MyStack {
queue<int> q_in; //用于存储栈内的元素
queue<int> q_tem; //为入栈操作的辅助队列
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q_tem.push(x);//添加元素队列头部
while(!q_in.empty()){//把q_in元素加入到q_tem
q_tem.push(q_in.front());
q_in.pop();
}
swap(q_tem,q_in);//交换两个元素
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int i = q_in.front();
q_in.pop();
return i;
}
/** Get the top element. */
int top() {
return q_in.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q_in.empty();
}
};
其实用单队列也可以实现,大致思路也是上面的两种,欢迎大家自己探索!