赞
踩
只用1个栈肯定不行,得用两个栈
思路:一个栈A,一个栈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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。