算法Sedgewick第四版-第1章基础-022一QueueWithTwoStacks
1 /****************************************************************************** 2 * Compilation: javac QueueWithTwoStacks.java 3 * Execution: java QueueWithTwoStacks < input.txt 4 * Dependencies: StdIn.java StdOut.java 5 * Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt 6 * 7 * A generic queue, implemented using two stacks. 8 * 9 * % java QueueWithTwoStacks < tobe.txt 10 * to be or not to be (2 left on queue) 11 * 12 ******************************************************************************/ 13 14 import java.util.NoSuchElementException; 15 16 public class QueueWithTwoStacks<Item> { 17 private Stack<Item> stack1; // back of queue 18 private Stack<Item> stack2; // front of queue 19 20 // create an empty queue 21 public QueueWithTwoStacks() { 22 stack1 = new Stack<Item>(); 23 stack2 = new Stack<Item>(); 24 } 25 26 // move all items from stack1 to stack2 27 private void moveStack1ToStack2() { 28 while (!stack1.isEmpty()) 29 stack2.push(stack1.pop()); 30 } 31 32 // is the queue empty? 33 public boolean isEmpty() { 34 return stack1.isEmpty() && stack2.isEmpty(); 35 } 36 37 38 // return the number of items in the queue. 39 public int size() { 40 return stack1.size() + stack2.size(); 41 } 42 43 // return the item least recently added to the queue. 44 public Item peek() { 45 if (isEmpty()) throw new NoSuchElementException("Queue underflow"); 46 if (stack2.isEmpty()) moveStack1ToStack2(); 47 return stack2.peek(); 48 } 49 50 // add the item to the queue 51 public void enqueue(Item item) { 52 stack1.push(item); 53 } 54 55 // remove and return the item on the queue least recently added 56 public Item dequeue() { 57 if (isEmpty()) throw new NoSuchElementException("Queue underflow"); 58 if (stack2.isEmpty()) moveStack1ToStack2(); 59 return stack2.pop(); 60 } 61 62 63 // a test client 64 public static void main(String[] args) { 65 QueueWithTwoStacks<String> q = new QueueWithTwoStacks<String>(); 66 while (!StdIn.isEmpty()) { 67 String item = StdIn.readString(); 68 if (!item.equals("-")) q.enqueue(item); 69 else if (!q.isEmpty()) StdOut.print(q.dequeue() + " "); 70 } 71 StdOut.println("(" + q.size() + " left on queue)"); 72 } 73 }
You can do anything you set your mind to, man!