-
Notifications
You must be signed in to change notification settings - Fork 1
/
5a) Queue Array.cpp
121 lines (98 loc) · 2.05 KB
/
5a) Queue 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
109
110
111
112
113
114
115
116
117
118
119
120
121
#include<iostream>
using namespace std;
class Queue{
private:
int size=0;
public:
int capacity;
int* arr;
int frontindex; // used to remove element from start
int rearindex; // used to add element at the end
Queue(int maxsize){
capacity = maxsize;
arr = new int[capacity];
frontindex = -1;
rearindex = -1;
}
void enqueue(int);
void dequeue();
int front(); // get the element which was added first
bool isempty();
bool isFull();
int getSize();
};
int Queue :: getSize(){
return size;
}
bool Queue :: isempty(){
return (getSize()==0);
}
bool Queue :: isFull(){
return (rearindex+1 == capacity);
}
void Queue :: enqueue(int val){
// adding at the end
if(isempty()){
frontindex = rearindex = 0 ;
arr[rearindex] = val;
size++;
}
else if(!isFull()){
rearindex += 1 ;
arr[rearindex] = val;
size++;
}
else{
cout << "Queue is full , cannot add more elements\n";
}
}
void Queue :: dequeue(){
// removing element from the front
if(frontindex<=rearindex){
frontindex += 1 ;
size--;
}
else{
cout << "\nQueue is empty cannot remove any element\n";
frontindex=-1;
rearindex=-1;
size = 0;
}
}
int Queue :: front(){
if(!isempty()){
return arr[frontindex];
}
return -1;
}
void display(Queue q){
if(q.isempty()){
cout << "Queue is empty nothing to display\n";
}
else{
while(!q.isempty()){
cout << q.front() << " " ;
q.dequeue();
}
}
cout << endl ;
}
int main(){
Queue q(5);
for(int i=1;i<=5;i++){
q.enqueue(i);
}
display(q);
for(int i=1;i<=5;i++){
q.dequeue();
}
display(q);
for(int i=10;i<=50;i+=10){
q.enqueue(i);
}
display(q);
q.dequeue();
display(q);
cout << endl;
return 0;
}