@author sibyjosek@gmail.com
The Queue Class
public class Queue { // outer class
class Data{ // an inner class
int d;
void show(){ System.out.print(" (" + d + ") "); } Data(int x){ d=x;} } Data q[]; int front, rear; int mSize; final String nullQ = "Empty Queue !!!", fullQ = "...Queue is Full !!!"; public Queue(int maximumSize){ mSize=maximumSize; q=new Data[mSize]; front=rear=-1; } boolean isEmpty(){ return front==-1; } boolean isFull(){ return front != -1 & (rear+1) % mSize == front; } Data first() throws Throwable{ if (isEmpty()) throw new Throwable(nullQ); return q[front]; } Data last() throws Throwable{ if (isEmpty()) throw new Throwable(nullQ); return q[rear]; } void add(Data data) throws Throwable{ if(front==-1) front=rear=0; else{ if (isFull()) throw new Throwable(fullQ); rear = (rear + 1) % mSize; } q[rear]=data; } void add(int data) throws Throwable{ add(new Data(data)); } Data delete() throws Throwable{ if(isEmpty()) throw new Throwable(nullQ); Data d=q[front]; if(front==rear) front=rear=-1; else front = (front + 1) % mSize; return d; } void show()throws Throwable{ if(isEmpty()) throw new Throwable(nullQ); System.out.println(); int i=front; do{ if( i == rear){ q[i].show(); break; } q[i].show(); i++; i %= mSize; }while(true); } protected void finalize() throws Throwable { super.finalize(); q=null; } }
Main - The Test Driver Class
public class Main { public static void main(String[] args) { Queue q=new Queue (5); try{ q.add(10); q.add(55); q.add(66); q.add(13); q.add(5); q.add(10001); }catch (Throwable e) { System.out.println(e.getMessage()); } try{ q.show(); //show current queue System.out.println("\nDeleting"); q.delete().show(); // show deleted item q.delete().show(); q.delete().show(); q.delete().show(); q.delete().show(); // all 5 items removed q.add(555555); q.add(555); q.add(5); System.out.println("\nNew Queue "); q.show(); // show current queue }catch (Throwable e) { System.out.println(e.getMessage()); } } }
The Output
...Queue is Full !!! (10) (55) (66) (13) (5) Deleting (10) (55) (66) (13) (5) New Queue (555555) (555) (5)