-
Notifications
You must be signed in to change notification settings - Fork 2
/
Queue impementation using array.cpp
108 lines (86 loc) · 2.11 KB
/
Queue impementation using array.cpp
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
//Simple implementation of a fixed sized Queue using an array
//the head and tail of the queue is circulated across the array
#include <iostream>
#include <cmath>
#include <cstdlib>
template <typename T>
class Queue{
private:
//head tail position, enqueue limit, and current number of elements in the queue
int head, tail, enqLmit, elementCount;
T* data;
public:
Queue(int cap){
enqLmit = cap;
data = new T[cap];
elementCount= 0;
head= 0;
tail= cap-1;
}
T& front(){
if(empty()){
std::cerr<<"Error: Attempt to take data form empty Queue!"<<std::endl;
exit(1);
}
return data[head];
}
T& back(void){
if(empty()){
std::cerr<<"Error: Attempt to take data form empty Queue!"<<std::endl;
exit(1);
}
return data[tail];
}
bool empty(void){
return (elementCount == 0);
}
bool full(void){
return (elementCount == enqLmit);
}
int size(void){
return elementCount;
}
int capacity(void){
return enqLmit;
}
void enqueue(const T& obj){
if(full()){
std::cerr<< "Queue overflow error!" <<std::endl;
return;
}
tail = (tail+1)%enqLmit;
data[tail]= obj;
elementCount++;
}
void dequeue(void){
if(empty()){
std::cerr<< "Queue underflow error!" <<std::endl;
return;
}
head = (head+1)%enqLmit;
elementCount--;
}
};
int main(void)
{
using std::cout;
using std::endl;
Queue<int> q(6);
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(5);
q.enqueue(6);
// q.enqueue(7); //Expect overflow
cout<< "is the queue full: " << q.full() <<endl;
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
// q.dequeue(); //Expect underflow
cout<< q.front() <<endl;
cout<< q.back() <<endl;
return 0;
}