All pastes #935768 Raw Edit

Unnamed

public text v1 · immutable
·published 2008-03-09 22:08 UTC
rendered paste body
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 <code>Token</code> 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 <code>true</code> if the queue is empty, <code>false</code>
   *         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());
	}

}