import java.util.NoSuchElementException; public class TokenStacksQueue implements TokenQueue { TokenArrayStack in; TokenArrayStack out; /** * Removes and returns the token at the front of the queue. * * @return the {@link Token} instance at the front of the queue * @throws java.util.NoSuchElementException * if the queue is empty */ public Token dequeue() throws NoSuchElementException{ if(isEmpty()) { throw new NoSuchElementException(); } if(out.isEmpty()){ while(!in.isEmpty()){ out.push(in.pop()); } } return (Token)out.pop(); } /** * Adds the given token to the rear of the queue. * * @param elem the {@link Token} instance that must be added * @return the Token instance that was added */ public Token enqueue(Token elem) { in.push(elem); return elem; } /** * Removes and returns the token at the front of the queue. * * @return the {@link Token} instance at the front of the queue * @throws java.util.NoSuchElementException * if the queue is empty */ public Token front() throws NoSuchElementException{ if(isEmpty()){ throw new NoSuchElementException(); } else if(out.isEmpty()) { while(!in.isEmpty()){ out.push(in.pop()); } } return (Token)out.pop(); } /** * Tells if the queue is empty. * * @return true if the queue is empty, false * otherwise. */ public boolean isEmpty() { return(in.isEmpty() && out.isEmpty()); } /** * Returns the size of the queue. * * @return a non-negative number */ public int size() { return(in.size() + out.size()); } }