-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueArrayCircular.java
More file actions
81 lines (71 loc) · 1.78 KB
/
QueueArrayCircular.java
File metadata and controls
81 lines (71 loc) · 1.78 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
public class QueueArrayCircular<T> {
// Attributes
private ArrayStatic<T> queue;
private int size;
private int capacity;
private int front;
private int rear;
// Constructors
public QueueArrayCircular() {
this.capacity = 10;
this.queue = new ArrayStatic<T>(this.capacity);
this.size = 0;
this.front = 0;
this.rear = 0;
}
public QueueArrayCircular(int capacity) {
this.capacity = capacity;
this.queue = new ArrayStatic<T>(this.capacity);
this.size = 0;
this.front = 0;
this.rear = 0;
}
// Methods
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public int size() {
return size;
}
public void enqueue(T data) {
if (isFull()) {
System.out.println("Queue is full");
return;
}
queue.set(rear, data);
rear = (rear + 1) % capacity;
size++;
}
public T dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return null;
}
T data = queue.get(front);
front = (front + 1) % capacity;
size--;
return data;
}
public T peek() {
if (isEmpty()) {
System.out.println("Queue is empty");
return null;
}
return queue.get(front);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(queue.get((front + i) % capacity));
if (i < size - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}