-
-
Notifications
You must be signed in to change notification settings - Fork 485
Expand file tree
/
Copy pathCircular_Queue.dart
More file actions
108 lines (93 loc) · 2.22 KB
/
Circular_Queue.dart
File metadata and controls
108 lines (93 loc) · 2.22 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import 'package:test/test.dart';
// author: kjain1810
// reference: https://en.wikipedia.org/wiki/Circular_buffer
const int MAX_SIZE = 10;
class CircularQueue<T> {
int start = -1, end = -1;
List<T> queue = []..length = MAX_SIZE;
// insert elements into the queue
void enque(T element) {
if (start == -1) {
start = 0;
end = 0;
queue[0] = element;
return;
}
if (end == MAX_SIZE - 1 && start == 0) {
print("The queue is full!!!");
return;
}
if (end == start - 1) {
print("The queue is full!!!");
return;
}
end++;
end %= MAX_SIZE;
queue[end] = element;
}
// remove elements from the queue
T deque() {
if (start == -1) {
print("The queue is empty!!!");
return null;
}
T here = queue[start];
if (start == end) {
start = -1;
end = -1;
return here;
}
start++;
start %= MAX_SIZE;
return here;
}
// get the size of the queue
int size() {
if (start == -1) return 0;
if (start < end) return end - start + 1;
return (MAX_SIZE - (start - end));
}
// print all the elements of the queue
void printAll() {
if (start == -1) {
print("The queue is empty!!!");
return;
}
int i = start;
while (i != end) {
i++;
i %= MAX_SIZE;
print(queue[i]);
}
}
}
void main() {
test("Initial CircularQueue is empty", () {
CircularQueue<int> queue = new CircularQueue<int>();
expect(queue.deque(), isNull);
});
test("deque return first item put to CircularQueue", () {
CircularQueue<int> queue = new CircularQueue<int>();
queue.enque(1);
expect(queue.deque(), equals(1));
});
test("CircularQueue act as fifo", () {
CircularQueue<int> queue = new CircularQueue<int>();
queue.enque(1);
queue.enque(2);
queue.enque(3);
expect(queue.deque(), equals(1));
expect(queue.deque(), equals(2));
expect(queue.deque(), equals(3));
});
test("deque returns null after removing all items", () {
CircularQueue<int> queue = new CircularQueue<int>();
queue.enque(1);
queue.enque(2);
queue.enque(3);
queue.deque();
queue.deque();
queue.deque();
expect(queue.deque(), isNull);
});
}