-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircular Queue
More file actions
81 lines (71 loc) · 1.91 KB
/
Circular Queue
File metadata and controls
81 lines (71 loc) · 1.91 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package DataS;
public class CircularQueue {
private int[] queue;
private int front;
private int rear;
private int size;
private int capacity;
public CircularQueue(int capacity) {
this.capacity = capacity;
queue = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public void enqueue(int item) {
if (isFull()) {
throw new IllegalStateException("Queue is full. Cannot enqueue " + item);
}
rear = (rear + 1) % capacity;
queue[rear] = item;
size++;
}
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty. Cannot dequeue.");
}
int item = queue[front];
front = (front + 1) % capacity;
size--;
return item;
}
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty. Cannot peek.");
}
return queue[front];
}
public void display() {
if (isEmpty()) {
System.out.println("Queue is empty.");
return;
}
System.out.print("Queue: ");
int count = 0;
int i = front;
while (count < size) {
System.out.print(queue[i] + " ");
i = (i + 1) % capacity;
count++;
}
System.out.println();
}
public static void main(String[] args) {
CircularQueue queue = new CircularQueue(5);
queue.enqueue(10);
queue.enqueue(12);
queue.enqueue(13);
queue.enqueue(14);
queue.enqueue(15);
queue.display();
System.out.println("Dequeue: " + queue.dequeue());
queue.display();
System.out.println("Peek: " + queue.peek());
}
}