Queue Data Structure

The Queue data structure allows for FIFO (first in – first out) functionality. Think of this as a simple line to a counter in a store.

public class Queue {

  // Initialize the set number of slots
  private int maxSize;

  // Array (slots) to maintain the data in
  private long[] queArray;

  // Index position for the element in the front
  private int front;

  // Index position for the element at the back
  private int rear;

  // Counter to maintain the number of items in the queue
  private int nItems;

  public Queue(int size) {
    this.maxSize = size;
    this.queArray = new long[size];
    front = 0;
    rear = -1; // no item in the array yet
    nItems = 0;
  }

  // Put to the end of queue
  public void insert(long j) {

    /** Create a circular queue, so each element that is
     * out of the array boundary will go to the beginning 
     * and override the
     * element there.
     */
    if (rear == maxSize - 1) {
      rear = -1;
    }

    rear++;
    queArray[rear] = j;
    nItems++;
  }

  // Remove from the front of queue
  public long remove() {
    long temp = queArray[front];
    front++;
    // reset front to the 0
    if (front == maxSize) {
      front = 0;
    }
    nItems--;
    return temp;
  }

  public long peakFront() {
    return queArray[front];
  }

  public boolean isEmpty() {
    return (nItems == 0);
  }

  public boolean isFull() {
    return (nItems == maxSize);
  }

  public void view() {
    System.out.print("[ ");
    for (int i = 0; i < queArray.length; i++) {
      System.out.print(queArray[i] + " ");
    }
    System.out.print("]");
  }
}

Make it work:

public static void main(String[] args) {
  Queue myQueue = new Queue(5);
  myQueue.insert(10);
  myQueue.insert(20);
  myQueue.insert(30);
  myQueue.insert(40);
  myQueue.insert(50);
}