My implementation:
public class Queue {
private int capacity;
private int currentSize;
private int[] arr;
public Queue(int capacity) {
this.capacity = capacity;
this.arr = new int[capacity];
this.currentSize = -1;
}
public int size() {
return currentSize + 1;
}
public boolean isEmpty() {
return currentSize == -1;
}
public boolean isFull() {
return currentSize == capacity - 1;
}
public void enqueue(int data) {
if(isFull()) {
System.out.println("Queue is full!");
} else {
arr[++currentSize] = data;
}
}
public int dequeue() {
int temp = arr[0];
if(!isEmpty()) {
for(int i = 0; i < size()-1; i++) {
arr[i] = arr[i+1];
}
currentSize--;
}
return temp;
}
//...
Other implementation:
public class Queue {
private int front, rear, size;
private int capacity;
private int[] array;
public Queue(int capacity) {
this.capacity = capacity;
this.front = this.size = 0;
this.rear = capacity - 1;
this.array = new int[this.capacity];
}
// Method to add an element to the queue
public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is full, cannot enqueue");
return;
}
this.rear = (this.rear + 1) % this.capacity;
this.array[this.rear] = item;
this.size++;
System.out.println(item + " enqueued to queue");
}
// Method to remove an element from the queue
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty, cannot dequeue");
return Integer.MIN_VALUE;
}
int item = this.array[this.front];
this.front = (this.front + 1) % this.capacity;
this.size--;
return item;
}
//...