Queue Implementation

REF.

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
import java.util.*;

// Class for queue
public class Queue {
private int[] arr; // array to store queue elements
private int front; // front points to front element in the queue
private int rear; // rear points to last element in the queue
private int capacity; // maximum capacity of the queue
private int count; // current size of the queue

// Constructor to initialize queue
Queue(int size) {
arr = new int[size];
capacity = size;
front = 0;
rear = 0;
count = 0;
}

// Utility function to remove front element from the queue
public void poll() {
// check for queue underflow
if (isEmpty()) {
System.out.println("UnderFlow\nProgram Terminated");
System.exit(1);
}

System.out.println("Removing " + arr[front]);

front = (front + 1) % capacity;
count--;
}

// Utility function to add an item to the queue
public void offer(int item) {
// check for queue overflow
if (isFull()) {
System.out.println("OverFlow\nProgram Terminated");
System.exit(1);
}

System.out.println("Inserting " + item);

arr[rear] = item;
rear = (rear + 1) % capacity;
count++;
}

// Utility function to return front element in the queue
public int peek() {
if (isEmpty()) {
System.out.println("UnderFlow\nProgram Terminated");
System.exit(1);
}
return arr[front];
}

// Utility function to return the size of the queue
public int size() {
return count;
}

// Utility function to check if the queue is empty or not
public Boolean isEmpty() {
return (size() == 0);
}

// Utility function to check if the queue is full or not
public Boolean isFull() {
return (size() == capacity);
}

}

0%