用栈实现队列
-
只用1个栈肯定不行,得用两个栈
-
思路:一个栈A,一个栈B
- 入队:栈A入栈,表示入队
- 出队:栈B有元素就出栈,没有元素就从A中所有元素出栈,都入B栈,再B出栈
-
代码:
public class StackQueue { private Stack<Integer> stackA = new Stack<Integer>(); private Stack<Integer> stackB = new Stack<Integer>(); /** * 入队操作: 直接入A栈 * @param element 入队的元素 */ public void enQueue(int element) { stackA.push(element); } /** * 出队操作:若B栈空了,则把A中元素都移入B栈 */ public Integer deQueue() { if(stackB.isEmpty()){ if(stackA.isEmpty()){ return null; } transfer(); } return stackB.pop(); } /** * 栈A元素转移到栈B */ private void transfer(){ while (!stackA.isEmpty()){ stackB.push(stackA.pop()); } } // 测试主代码 public static void main(String[] args) throws Exception { StackQueue stackQueue = new StackQueue(); stackQueue.enQueue(1); stackQueue.enQueue(2); stackQueue.enQueue(3); System.out.println(stackQueue.deQueue()); System.out.println(stackQueue.deQueue()); stackQueue.enQueue(4); System.out.println(stackQueue.deQueue()); System.out.println(stackQueue.deQueue()); } }
-
思考:入队的时间复杂度显然是 O ( 1 ) O(1) O(1),出队涉及AB两栈的迁移。迁移时时间复杂度为 O ( n ) O(n) O(n),不迁移就是 O ( 1 ) O(1) O(1)。这是均摊时间复杂度,均摊到每次出队上就是 O ( 1 ) O(1) O(1)