pop & peek:除最后一个元素之外的所有元素,添加到 queue2 中,再交换两个队列的引用;
empty:检测 queue1 的大小即可;
难点:
Q1:两种方法的区别?
Approach 1:将 queue2 中的所有元素重新添加到 queue1 中;
Approach 2:交换两个队列的引用;
A1:Approach 2 效率更高;
classMyStack{
Queue<Integer> queue1;
Queue<Integer> queue2;/** Initialize your data structure here. */publicMyStack(){
queue1 =newLinkedList<>();
queue2 =newLinkedList<>();}/** Push element x onto stack. */publicvoidpush(int x){
queue1.add(x);}/** Removes the element on top of the stack and returns that element. */publicintpop(){while(queue1.size()>1){
queue2.add(queue1.poll());}
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;return queue2.poll();}/** Get the top element. */publicinttop(){while(queue1.size()>1){
queue2.add(queue1.poll());}int ans = queue1.poll();
queue2.add(ans);
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;return ans;}/** Returns whether the stack is empty. */publicbooleanempty(){return queue1.isEmpty()&& queue2.isEmpty();}}
classMyStack{
Queue<Integer> queue;/** Initialize your data structure here. */publicMyStack(){
queue =newLinkedList<>();}/** Push element x onto stack. */publicvoidpush(int x){
queue.add(x);for(int i = queue.size()-1; i >0; i--)
queue.add(queue.poll());}/** Removes the element on top of the stack and returns that element. */publicintpop(){return queue.poll();}/** Get the top element. */publicinttop(){return queue.peek();}/** Returns whether the stack is empty. */publicbooleanempty(){return queue.isEmpty();}}
2. LeetCode 232
2.1 复杂度分析
LeetCode 232 和 225 对比:
LeetCode 225:用队列实现栈,用单个队列或两个队列均可;
LeetCode 232:用栈实现队列,用两个栈实现;
两个栈:
push:
时间复杂度:O(1);
空间复杂度:O(n);
pop:
时间复杂度:O(n);
空间复杂度:O(1);
peek:
时间复杂度:O(n);
空间复杂度:O(1);
empty:
时间复杂度:O(1);
空间复杂度:O(1);
2.2 两个栈
解题思路:
stack1 保存当前所有元素;
push:将新元素添加到 stack1 中;
pop & peek:将 stack1 中的所有元素添加到 stack2 中,实现栈中现有元素的逆序排放;
empty:检测 stack1 的大小即可;
难点:
Q1:两种方法的区别?
Approach 1:每次 push 新元素时,将栈中所有元素逆序存放;
Approach 2:仅当执行 pop、peek 操作时,将栈中所有元素逆序存放;
A1:Approach 2 能减少不必要的操作;
classMyQueue{
Stack<Integer> stack1;
Stack<Integer> stack2;/** Initialize your data structure here. */publicMyQueue(){
stack1 =newStack<>();
stack2 =newStack<>();}/** Push element x to the back of queue. */publicvoidpush(int x){
stack1.push(x);}/** Removes the element from in front of queue and returns that element. */publicintpop(){if(stack2.isEmpty())while(!stack1.isEmpty())
stack2.push(stack1.pop());return stack2.pop();}/** Get the front element. */publicintpeek(){if(stack2.isEmpty())while(!stack1.isEmpty())
stack2.push(stack1.pop());return stack2.peek();}/** Returns whether the queue is empty. */publicbooleanempty(){return stack1.isEmpty()&& stack2.isEmpty();}}