-
Notifications
You must be signed in to change notification settings - Fork 637
/
Copy pathCircular_queue.java
75 lines (62 loc) · 1.63 KB
/
Circular_queue.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
public class CircularQueue {
private int[] arr;
private int front;
private int rear;
private int capacity;
private int size;
public CircularQueue(int capacity) {
this.capacity = capacity;
this.arr = new int[capacity];
this.front = -1;
this.rear = -1;
this.size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public void enqueue(int element) {
if (isFull()) {
System.out.println("Queue is full. Cannot enqueue more elements.");
return;
}
if (isEmpty()) {
front = 0;
}
rear = (rear + 1) % capacity;
arr[rear] = element;
size++;
}
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue elements.");
return -1;
}
int element = arr[front];
if (front == rear) {
front = -1;
rear = -1;
} else {
front = (front + 1) % capacity;
}
size--;
return element;
}
public int front() {
if (isEmpty()) {
System.out.println("Queue is empty. No front element.");
return -1;
}
return arr[front];
}
}
public static void main(String[] args) {
CircularQueue queue = new CircularQueue(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.dequeue()); // Output: 1
System.out.println(queue.front()); // Output: 2
}