-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircularQueueExample.java
91 lines (77 loc) · 2.7 KB
/
CircularQueueExample.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public class CircularQueueExample {
// CircularQueue class definition
static class CircularQueue {
private int[] queue; // Array to store the elements of the queue
private int front, rear, size; // Variables to keep track of the front, rear, and size of the queue
// Constructor to initialize the queue with a given size
public CircularQueue(int size) {
this.size = size;
this.queue = new int[size];
this.front = -1;
this.rear = -1;
}
// Method to check if the queue is full
public boolean isFull() {
return (front == 0 && rear == size - 1) || (rear == (front - 1) % (size - 1));
}
// Method to check if the queue is empty
public boolean isEmpty() {
return front == -1;
}
// Method to add an element to the queue
public void enqueue(int element) {
if (isFull()) {
System.out.println("Queue is full");
return;
}
if (front == -1) {
front = 0;
}
rear = (rear + 1) % size;
queue[rear] = element;
}
// Method to remove and return the front element from the queue
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
int element = queue[front];
if (front == rear) {
front = -1;
rear = -1;
} else {
front = (front + 1) % size;
}
return element;
}
// Method to return the front element without removing it
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
return queue[front];
}
}
// Main method to demonstrate the CircularQueue usage
public static void main(String[] args) {
CircularQueue cq = new CircularQueue(5); // Create a circular queue with size 5
// Add elements to the queue
cq.enqueue(10);
cq.enqueue(20);
cq.enqueue(30);
cq.enqueue(40);
cq.enqueue(50);
// Remove and print an element from the queue
System.out.println("Dequeued element: " + cq.dequeue());
// Print the front element
System.out.println("Front element: " + cq.peek());
// Add another element to the queue
cq.enqueue(60);
// Remove and print all elements from the queue
while (!cq.isEmpty()) {
System.out.println("Dequeued element: " + cq.dequeue());
}
}
}