Thursday, March 07, 2013

Data Structures - Queue

A Queue is an example of a linear data structure - a sequential
collection, and it is a FIFO structure. Anything that's inserted
first, will be the first to leave. We need to maintain two pointers,
the start and the end. An efficient implementation of Queue performs
the operations - enqueue (insert) and dequeue (remove) - in O(1) time.

Below is a sample implementation of a Queue (Java Data Structures (2nd edition))

public class Queue {
 private Object[] objArray;
 private int start, end;
 private boolean full;

 public Queue(final int maxSize) {
  objArray = new Object[maxSize];
  start = end = 0;
  full = false;
 }

 public boolean isEmpty() {
  return (start == end) && !full;
 }

 public boolean isFull() {
  return full;
 }

 public void insert(final Object o) {
  if (!full) {
   objArray[start = (++start % objArray.length)] = o;
  }
  

  if (start == end) {
   full = true;
  }
 }

 public Object remove() {
  if (full) {
   full = false;
  } else if (isEmpty()) {
   return null;
  }

  return objArray[end = (++end % objArray.length)];
 }

 public String toString() {
  StringBuilder sbr = new StringBuilder();
  for (int i = 0; i < objArray.length; i++) {
   sbr.append(objArray[i]);
  }
  return sbr.toString();
 }
}

No comments: