You are on page 1of 1

1 public class QueueArray {

2 private int first, last, size, count;


3 private Object[] storage;
4 //first and last referst to the first and last elements in the Queue
5 //size refers to the size of the Queue
6 //count refers to the number of elements that are there in the Queue
7
8 public QueueArray(int n) {
9 first = 0;last = -1; count = 0; size = n;
10 storage = new Object[n];
11 //Last is set to -1 because we have to move right, if we add an element into
the queue
12 }
13
14 public boolean isFull(){
15 return count >= size;
16 }
17
18 public boolean isEmpty(){
19 return count == 0;
20 }
21
22 public void enqueue(Object el) throws Exception {
23 if (!isFull()) //Before inserting into the queue, we need to find whether
the Queue is full or not.
24 {
25 last = (last+1)%size;
26 count++;
27 storage[last] = el;
28 }
29 else throw new Exception ("Queue is Full");
30 }
31
32 public Object dequeue() throws Exception {
33 if (!isEmpty()) //Before deleting from the queue, we need to find whether
there is an element in the queue;
34 {
35 Object tmp = storage[first];
36 first = (first+1)%size;
37 count--;
38 return tmp;
39 }
40 else throw new Exception ("Queue is Empty");
41 }
42
43 public static void main (String[] args) throws Exception
44 {
45 QueueArray qa = new QueueArray(3);
46 qa.enqueue(3);
47 qa.enqueue(10);
48 System.out.println(qa.dequeue());
49 System.out.println(qa.dequeue());
50
51 //System.out.println(qa.dequeue());
52
53 qa.enqueue(11);
54 qa.enqueue(12);
55 qa.enqueue(13);
56 qa.enqueue(14);
57
58 }
59 }
60

You might also like