Leetcode 刷题日记
2021.2.7
题目链接:
https://leetcode-cn.com/problems/implement-stack-using-queues/submissions/
问题描述:
用队列实现栈
解答1:
双队列实现
代码:
import java.util.LinkedList;
class MyStack {
LinkedList<Integer> queue1 = new LinkedList<>();
LinkedList<Integer> queue2 = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
if(queue1.isEmpty()){
queue1.addFirst(x);
pour(queue2,queue1);
}else if(queue2.isEmpty()){
queue2.addFirst(x);
pour(queue1,queue2);
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(!queue1.isEmpty()) return queue1.removeFirst();
else if(!queue2.isEmpty()) return queue2.removeFirst();
return -1;
}
/** Get the top element. */
public int top() {
if(!queue1.isEmpty()) return queue1.getFirst();
else if(!queue2.isEmpty()) return queue2.getFirst();
return -1;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty() && queue2.isEmpty();
}
private static void pour(LinkedList<Integer> from,LinkedList<Integer> to){
while(!from.isEmpty()){
to.addLast(from.removeFirst());
}
}
}
分析:
时间复杂度:
push():O(n)
pop():O(1)
top:O(1)
empty:O(1)
空间复杂度:
push():O(n)
pop():O(n)
top:O(n)
empty:O(n)
运行结果:
评注:
这和使用两个栈实现队列有相似之处
(利用栈实现队列的题目链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
该题博文链接:
https://blog.csdn.net/m0_51404298/article/details/113744309
)
这道题的意义就是建立起栈和队列的联系,用辩证统一的观点来看待问题。
解答2:
单队列实现(不符合题意但更加简单)
代码:
import java.util.LinkedList;
class MyStack {
LinkedList<Integer> queue = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
queue.push(x);
for (int i = 0; i < queue.size() - 1; i++) {
queue.push(queue.removeFirst());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.removeFirst();
}
/** Get the top element. */
public int top() {
return queue.getFirst();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
System.out.println(stack.top());
}
}
分析:
时间复杂度:
push():O(n)
pop():O(1)
top:O(1)
empty:O(1)
空间复杂度:
push():O(n)
pop():O(n)
top:O(n)
empty:O(n)
运行结果:
评注:
实际上用一个队列就能实现栈,思路就是先让被压入的元素入队,然后让前面的元素依次出队后再入队。这样就能保证push()和top()都是常数时间开销。