-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathCircular-queue.java
More file actions
53 lines (46 loc) · 1.29 KB
/
Circular-queue.java
File metadata and controls
53 lines (46 loc) · 1.29 KB
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
class CircularQueue {
private int[] arr;
private int front, rear, size, capacity;
public CircularQueue(int capacity) {
this.capacity = capacity;
arr = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
public void enqueue(int data) {
if (size == capacity) throw new RuntimeException("Queue is full");
rear = (rear + 1) % capacity;
arr[rear] = data;
size++;
}
public int dequeue() {
if (size == 0) throw new RuntimeException("Queue is empty");
int val = arr[front];
front = (front + 1) % capacity;
size--;
return val;
}
public int peek() {
if (size == 0) throw new RuntimeException("Queue is empty");
return arr[front];
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public static void main(String[] args) {
CircularQueue cq = new CircularQueue(5);
cq.enqueue(1);
cq.enqueue(2);
cq.enqueue(3);
cq.enqueue(4);
cq.enqueue(5);
System.out.println(cq.dequeue());
System.out.println(cq.peek());
cq.enqueue(6);
while (!cq.isEmpty()) System.out.print(cq.dequeue() + " ");
}
}