/***********************************************
* CS2510 Spring 2011
* Lecture #19 Afternoon
* A Queue with 2 Stacks
***********************************************/
import tester.*;
import image.*;
import world.*;
import java.util.ArrayList;
/** Represents a using an */
class Stack{
ArrayList stack = new ArrayList();
/** Push the given element onto the top of this Stack */
void push(X x){
this.stack.add(x);
}
/** Take a look at this stack's top element */
X peek(){
return this.stack.get(this.stack.size()-1);
}
/** Remove (and return) this stack's top element */
X pop(){
return this.stack.remove(this.stack.size()-1);
}
/** Does this stack have any elements? */
boolean isEmpty(){
return this.stack.isEmpty();
}
}
/** Implement a using two */
class Queue{
Stack inStk = new Stack();
Stack outStk = new Stack();
/** Add the given element to the "back" of this Queue */
void enqueue(W w){
this.inStk.push(w);
}
/** Helper to shift the in" */
private void restack(){
// Move all the elements from the inStk to the outStack
if(!this.inStk.isEmpty()){
this.two.push(this.one.pop());
this.restack();
}
}
/** Remove (and return) an element from the "front" of this Queue */
W dequeue(){
// No Elements!
if(this.isEmpty()){
throw new Mimi("Bad News!");
}
// No outStk elements... move them from the inStk
if(this.outStk.isEmpty()){
this.restack();
}
// Must succeed! :)
return this.outStk.pop();
}
/** Look at the element at the "front" of this Queue */
W front(){
// No Elements!
if(this.isEmpty()){
throw new Mimi("Bad News!");
}
// No outStk elements... move them from the inStk
if(this.outStk.isEmpty()){
this.restack();
}
return this.outStk.peek();
}
/** Does this queue have any elements? */
boolean isEmpty(){
return this.inStk.isEmpty() && this.outStk.isEmpty();
}
}
/** Represents a custom error condition */
class Mimi extends RuntimeException{
Mimi(String msg){
super(msg);
}
}
/** Examples and Tests */
class LectureExamples{
void testQueue(Tester t){
Queue q = new Queue();
q.enqueue(2.5);
q.enqueue(4.0);
q.enqueue(105.1);
q.enqueue(19.69);
t.checkExpect(q.front(), 2.5);
t.checkExpect(q.dequeue(), 2.5);
t.checkExpect(q.front(), 4.0);
t.checkExpect(q.dequeue(), 4.0);
t.checkExpect(q.isEmpty(), false);
q.dequeue();
q.dequeue();
t.checkExpect(q.isEmpty(), true);
}
}