Queue

What is a Queue?

  • Property of Queue

    • follows FIFO(First In First Out) method
  • Reason why learning

    • When we need to create an application which utilizes “first incoming data first”.



Implementation options of Queue

  • Array
    • Linear Queue
    • Circular Queue

  • Linked list
    • Linear Queue



Linear Queue by Array

QueueByArray.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.chung;
public class QueueByArray{

int[] arr;
int topOfQueue;
int beginningOfQueue;


public QueueByArray(int size) {
this.arr = new int[size];
this.topOfQueue = -1;
this.beginningOfQueue = -1;
System.out.println("Successfully created an empty queue of size: "+size);
}//end of method


public void enQueue(int value) {
if (isQueueFull()) {
System.out.println("Queue overflow error!!");
}else if (isQueueEmpty()) { //If the queue is empty then we need to initialize beginning index
beginningOfQueue=0;
topOfQueue++;
arr[topOfQueue] = value;
System.out.println("Successfully inserted "+value+" in the queue");
}else { //if the queue already has some elements in it then no need to initialize beginning index
topOfQueue++;
arr[topOfQueue] = value;
System.out.println("Successfully inserted "+value+" in the queue");
}
printQueue();
}//end of method


public void printQueue() {
if(!isQueueEmpty()) {
System.out.println("Queue now ...");
for(int i=beginningOfQueue; i<=topOfQueue; i++) {
System.out.println(arr[i] + " ");
}
System.out.println();
}else {
System.out.println("Queue is empty !");
}
}

public void deQueue() {
if (isQueueEmpty()) {
System.out.println("Queue underflow error!!");
} else {
System.out.println("Dequeing value from Queue...");
System.out.println("Dequeued: "+arr[beginningOfQueue]+" from queue");
beginningOfQueue++;
if(beginningOfQueue > topOfQueue) { //If last element in the Queue is Dequeued
beginningOfQueue = topOfQueue = -1;
}
}
printQueue();
System.out.println();
}//end of method


public boolean isQueueEmpty() {
if ((beginningOfQueue == -1) || (beginningOfQueue == arr.length))
return true;
else
return false;
}//end of method


public boolean isQueueFull() {
if (topOfQueue == arr.length-1) {
return true;
}
else {
return false;
}

}//end of method


public void peekOperation() {
if (!isQueueEmpty()) {
System.out.println(arr[beginningOfQueue]);
}else {
System.out.println("The queue is empty!!");
}
}//end of method


public void deleteQueue() {
arr = null;
System.out.println("Queue is successfully deleted !");
}//end of method

}//end of class