-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircular Queue in Java
More file actions
83 lines (74 loc) · 2.01 KB
/
Circular Queue in Java
File metadata and controls
83 lines (74 loc) · 2.01 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
82
83
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()) {
System.out.println("Queue is full. Cannot enqueue " + item);
return;
}
rear = (rear + 1) % capacity;
queue[rear] = item;
size++;
}
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue.");
return -1;
}
int item = queue[front];
front = (front + 1) % capacity;
size--;
return item;
}
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot peek.");
return -1;
}
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(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(6); // Queue is full
queue.display(); // Queue: 1 2 3 4 5
System.out.println("Dequeue: " + queue.dequeue()); // Dequeue: 1
queue.display(); // Queue: 2 3 4 5
System.out.println("Peek: " + queue.peek()); // Peek: 2
}
}