题目原文:
Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations.
题目要求用栈实现队列的所有操作。
1 package week2; 2 3 import java.util.Stack; 4 5 /** 6 * Queue with two stacks. Implement a queue with two stacks so that each queue 7 * operations takes a constant amortized number of stack operations 8 * @author yangjingjing 9 * 10 */ 11 public class QueueWith2Stacks<E>{ 12 Stack<E> inStack = new Stack<E>(); 13 Stack<E> outStack = new Stack<E>(); 14 public boolean isEmpty(){ 15 if(inStack.isEmpty() && outStack.isEmpty()) 16 return true; 17 else return false; 18 } 19 public int size(){ 20 return (inStack.size() + outStack.size()); 21 } 22 public void enqueue(E item){ 23 inStack.push(item); 24 } 25 public E dequeue(){ 26 if(outStack.isEmpty()){ 27 if(inStack.isEmpty()) return null; 28 else{ 29 while(!inStack.isEmpty()) { 30 outStack.push(inStack.pop()); 31 } 32 return outStack.pop(); 33 } 34 }else{ 35 return outStack.pop(); 36 } 37 } 38 public static void main(String[] args) { 39 QueueWith2Stacks<Object> queue = new QueueWith2Stacks<Object>(); 40 queue.enqueue("a"); 41 queue.enqueue("b"); 42 queue.enqueue("c"); 43 System.out.println(queue.dequeue()); 44 queue.enqueue(1); 45 queue.enqueue(2); 46 Object o = null; 47 while((o = queue.dequeue()) != null) { 48 System.out.println(o); 49 } 50 } 51 }