题目描述
我的解法
思路
将一个队列作为备份,栈的pop和top操作需要取尾部元素时,将一个队列里的元素转移到另一个中,转移中的最后一个元素即为所需,处理完再转移回来
对应Java代码
class MyStack {
private Queue<Integer> qu1,qu2;
/** Initialize your data structure here. */
public MyStack() {
qu1 = new LinkedList<Integer>();
qu2 = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
qu1.add(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int t = 0;
while(qu1.peek() != null){
t = qu1.poll();
if(qu1.peek() != null){
qu2.add(t);
}
}
while(qu2.peek() != null){
qu1.add(qu2.poll());
}
return t;
}
/** Get the top element. */
public int top() {
int t = 0;
while(qu1.peek() != null){
t = qu1.poll();
qu2.add(t);
}
while(qu2.peek() != null){
qu1.add(qu2.poll());
}
return t;
}
/** Returns whether the stack is empty. */
public boolean empty() {
if(qu1.peek() == null){
return true;
} else {
return false;
}
}
}
/**
* 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();
* boolean param_4 = obj.empty();
*/
复杂度分析
时间复杂度:O() push为O(1) top和pop为O(n)
空间复杂度:O(n)
更优解法
此部分转载于官方题解
思路
思路是一样的,还是实现方式上有更多精妙的地方:
- 将队列的头作为栈的尾部,这样pop和top操作就可以实现
- 对应上面的方法,只需要在push时将新元素送到队列尾部
对应Java代码
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
public void push(int x) {
queue2.offer(x);
while (!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}
作者:demigodliu
链接:https://leetcode-cn.com/problems/implement-stack-using-queues/solution/wu-tu-guan-fang-tui-jian-ti-jie-yong-dui-63d4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
复杂度分析
时间复杂度:入栈操作是O(n),其余操作是O(1)
空间复杂度:O(n) 其中n是栈内的元素,需要使用两个队列存储栈内的元素
收获总结
实际上本题使用一个队列也可以实现,使用一个队列时,为了满足栈的特性,即最后入栈的元素最先出栈,同样需要满足队列前段的元素是最后入栈的元素
对应的具体操作就是
queue.offer(queue.poll())