forked from krish-ag/HacktoberFest22-Repo-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicQueueUsingArrays
111 lines (88 loc) · 1.86 KB
/
DynamicQueueUsingArrays
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
109
110
111
//Dynamic Queue Implementation using arrays and templates
#include <iostream>
using namespace std;
template <typename T>
class queueUsingArray{
private:
T * data;
int firstIndex;
int nextIndex;
int size;
int capacity;
public:
queueUsingArray(int s){
data = new T[s];
firstIndex = -1;
nextIndex = 0;
size = 0;
capacity = s;
}
int getSize(){
return size;
}
bool isEmpty(){
return size == 0;
}
void enqueue(T element){
if(size == capacity){
T * newData = new T[2*capacity];
int j = 0;
for(int i = firstIndex ; i < capacity ; i++){
newData[j] = data[i];
j++;
}
for(int i = 0 ; i < firstIndex ; i++){
newData[j] = data[i];
j++;
}
delete [] data;
data = newData;
firstIndex = 0;
nextIndex = capacity;
capacity = capacity * 2;
}
data[nextIndex] = element;
nextIndex = (nextIndex + 1) % capacity;
if(firstIndex == -1){
firstIndex = 0;
}
size++;
}
T front(){
if(isEmpty()){
cout << "Queue is Empty!" << endl;
return 0;
}
return data[firstIndex];
}
T dequeue(){
if(isEmpty()){
cout << "Queue is Empty!" << endl;
return 0;
}
T ans = data[firstIndex];
firstIndex = (firstIndex + 1) % capacity;
size --;
if(size == 0){
firstIndex = -1;
nextIndex = 0;
}
return ans;
}
};
int main(){
queueUsingArray<int> s(5);
s.enqueue(10);
s.enqueue(20);
s.enqueue(30);
s.enqueue(40);
s.enqueue(50);
s.enqueue(60);
cout << s.front() << endl; //Prints 10
cout<< s.dequeue() << endl; // Deletes and prints 10
cout<< s.dequeue() << endl; // Deletes and prints 20
cout<< s.dequeue() << endl; // Deletes and prints 30
cout << s.getSize() << endl; // Prints 3
cout << s.isEmpty() << endl; // Prints 0(FALSE)
return 0;
}