-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
83 lines (67 loc) · 2.03 KB
/
CircularQueue.java
File metadata and controls
83 lines (67 loc) · 2.03 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
// this idea is being used in the implementation of the circular buffer in the operating system.
// instead of copying things into and out of the buffer, we just move the pointers around.
// why is this useful? because it's faster and more efficient?
// the circular buffer is a fixed-size buffer that handles data in a circular fashion.
// draw some sketches of how this alogrithm works.
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; // huh??
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; // huh??
}
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
}
}