-
Notifications
You must be signed in to change notification settings - Fork 3
/
ArrayQueue.h
71 lines (61 loc) · 1020 Bytes
/
ArrayQueue.h
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
/*
* ArrayQueue.h
*
* Created on: 2011-11-23
* Author: morin
*/
#ifndef ARRAYQUEUE_H_
#define ARRAYQUEUE_H_
#include "array.h"
namespace ods {
template<class T>
class ArrayQueue {
protected:
array<T> a;
int j;
int n;
void resize();
public:
ArrayQueue();
virtual ~ArrayQueue();
virtual bool add(T x);
virtual T remove();
int size();
};
template<class T>
ArrayQueue<T>::ArrayQueue() : a(1) {
n = 0;
j = 0;
}
template<class T>
ArrayQueue<T>::~ArrayQueue() {
delete a;
}
template<class T>
void ArrayQueue<T>::resize() {
array<T> b(max(1, 2*n));
for (int k = 0; k < n; k++)
b[k] = a[(j+k)%a.length];
a = b;
}
template<class T>
bool ArrayQueue<T>::add(T x) {
if (n + 1 > a.length) resize();
a[(j+n) % a.length] = x;
n++;
return true;
}
template<class T>
T ArrayQueue<T>::remove() {
T x = a[j];
j = (j + 1) % a.length;
n--;
if (a.length >= 3*n) resize();
return x;
}
template<class T>
int ArrayQueue<T>::size() {
return n;
}
} /* namespace ods */
#endif /* ARRAYQUEUE_H_ */