Queue

Queue is a linear data structure that follows the First In First Out (FIFO) principle. Elements are added at the rear (enqueue) and removed from the front (dequeue).

Circular Queue

A circular queue is a linear data structure that follows the FIFO principle but connects the end of the queue back to the front, forming a circle. This allows for efficient use of space by reusing empty slots created by dequeued elements.

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
public class CircularQueue {
private String[] items;
private int n = 0;
private int head = 0;
private int tail = 0;

public CircularQueue(int capacity) {
items = new String[capacity];
n = capacity;
}

public boolean enqueue(String item) {
if ((tail + 1) % n == head) return false;
items[tail] = item;
tail = (tail + 1) % n;
return true;
}

public String dequeue() {
if (head == tail) return null;
String ret = items[head];
head = (head + 1) % n;
return ret;
}
}