用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
固定使用Stack1来压栈
固定使用Stack2来弹栈
压栈时,直接压入Stack1中,
弹栈的时候,若Stack2中为空,则将Stack1全部弹栈压入,即得到栈反转后队列
若Stack2不为空,则说明仍有部分前序队列没弹栈完毕,继续弹栈
模拟场景(栈顶在右)
操作 | Stack1 | Stack2 | |
---|---|---|---|
A,B,C入栈 | A,B,C | ||
弹栈1次 | (弹栈前) | C,B,A | |
弹栈1次 | (开始弹栈) | C,B | |
D入栈 | D | C,B | |
弹栈一次 | D | C | |
E,F入栈 | D,E,F | C | |
弹栈一次 | D,E,F | ||
弹栈一次 | (弹栈前) | F,E,D | |
弹栈一次 | (开始弹栈) | F,E |
时间复杂度 压栈O(1) 弹栈O(n)
具体实现:
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);
return;
}
public int pop() {
//预存队列已空,更新
if(stack2.empty()){
//stack1中内容全部转入stack2中作为队列
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
//弹栈顶(队列头)出来
return stack2.pop().intValue();
}
}
网友评论