1 /******************************************************************************2 * Compilation:javac Queuewithtwostacks.java3 * Execution:java Queuewithtwostacks < Input.txt4 * Dependencies:StdIn.java Stdout.java5 * Data Files:Http://algs4.cs.princeton.edu/13stacks/tobe.txt 6 *7 * A generic queue, implemented using the stacks.8 *9 *% java queuewithtwostacks < tobe.txtTen * To IS or not to is (2 left on queue) One * A ******************************************************************************/ - - Importjava.util.NoSuchElementException; the - Public classQueuewithtwostacks<item> { - PrivateStack<item> Stack1;//Back of the queue - PrivateStack<item> Stack2;//front of the queue + - //Create an empty queue + Publicqueuewithtwostacks () { AStack1 =NewStack<item>(); atStack2 =NewStack<item>(); - } - - //move all items from Stack1 to Stack2 - Private voidMovestack1tostack2 () { - while(!stack1.isempty ()) in Stack2.push (Stack1.pop ()); - } to + //is the queue empty? - Public BooleanIsEmpty () { the returnStack1.isempty () &&stack2.isempty (); * } $ Panax Notoginseng - //Return the number of items in the queue. the Public intsize () { + returnStack1.size () +stack2.size (); A } the + //return the item least recently added to the queue. - PublicItem Peek () { $ if(IsEmpty ())Throw NewNosuchelementexception ("Queue underflow"); $ if(Stack2.isempty ()) Movestack1tostack2 (); - returnStack2.peek (); - } the - //Add the item to the queueWuyi Public voidEnqueue (item item) { the Stack1.push (item); - } Wu - //Remove and return the item on the queue least recently added About PublicItem dequeue () { $ if(IsEmpty ())Throw NewNosuchelementexception ("Queue underflow"); - if(Stack2.isempty ()) Movestack1tostack2 (); - returnStack2.pop (); - } A + the //a test client - Public Static voidMain (string[] args) { $queuewithtwostacks<string> q =NewQueuewithtwostacks<string>(); the while(!Stdin.isempty ()) { theString item =stdin.readstring (); the if(!item.equals ("-") ) Q.enqueue (item); the Else if(!q.isempty ()) Stdout.print (Q.dequeue () + ""); - } inStdout.println ("(" + q.size () + "left on queue")); the } the}
Algorithm Sedgewick Fourth Edition-1th Chapter Foundation-221 Queuewithtwostacks