5、用两个栈实现队列
题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
栈是先进后出,队列是先进先出。
出队时把已入栈Stack1
元素全部先出栈压入栈Stack2
再从Stack2
出栈就能使先进的元素位于栈顶从而先出。
入队时注意要先判断Stack2
是否为空,若不空一定要把元素再次出栈压入Stack1
之后再执行入队操作,否则留在Stack2
中的元素无法先出,会被再次入栈Stack1
的元素压在下面。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(!stack2.empty()){
stack1.push(stack2.pop());
}
stack1.push(node);
}
public int pop() {
if(stack1.empty()&&stack2.empty()){
throw new RuntimeException("Queue is empty!");
}
while(!stack1.empty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
优化思路:
出队时先判断Stack2
是否为空,若空则先把Stack1
中元素弹出压入Stack2
再出栈,若不空先出栈Stack2
中的元素,避免Stack1
中弹出的元素压入不空的Stack2
之后造成出栈顺序错误。
不需要将Stack2
中未出栈元素再次压入Stack1
,降低时间复杂度,唯一的缺点是当push操作积攒的数据过多时,下一次pop操作的开销会变得很大,从而导致pop操作的开销不稳定;解决方法应该是,在push中设置阀值,以提升pop操作的稳定性(此处缺点了解即可)。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.empty()&&stack2.empty()){
throw new RuntimeException("Queue is empty!");
}
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}