-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcircular_queue.h
More file actions
70 lines (55 loc) · 1.39 KB
/
circular_queue.h
File metadata and controls
70 lines (55 loc) · 1.39 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
//
// Created by codercat on 19-3-12.
//
#ifndef ALGORITHM_CIRCULARQUEUE_H
#define ALGORITHM_CIRCULARQUEUE_H
#include <cassert>
template<typename E>
class CircularQueue {
private:
unsigned int capacity = 0;
unsigned int size = 0;
E *container = NULL;
int frontIndex = 0;
int tailIndex = 0;
int getNextIndex(int index) {
return (int)(index + 1) % this->capacity;
}
public:
CircularQueue(unsigned int capacity) {
assert(capacity > 0);
this->capacity = capacity;
this->frontIndex = 0;
this->tailIndex = 0;
this->container = new E[capacity];
}
void enqueue(E e) {
assert(!this->isFull());
this->container[this->tailIndex] = e;
this->tailIndex = this->getNextIndex(this->tailIndex);
this->size ++;
}
E dequeue() {
assert(!this->isEmpty());
E front = this->container[this->frontIndex];
this->frontIndex = this->getNextIndex(this->frontIndex);
this->size --;
return front;
}
bool isEmpty() {
return this->getSize() == 0;
}
bool isFull() {
return this->getSize() == this->capacity;
}
E getFront() {
return this->container[this->frontIndex];
}
unsigned int getSize() {
return this->size;
}
~CircularQueue() {
free(this->container);
}
};
#endif //ALGORITHM_CIRCULARQUEUE_H