Repository navigation
Expand file tree
/
Copy pathcircular queue using array.cpp
More file actions
129 lines (100 loc) · 2.6 KB
/
Copy pathcircular queue using array.cpp
File metadata and controls
129 lines (100 loc) · 2.6 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
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
122
123
124
125
126
127
128
129
#include<bits/stdc++.h>
using namespace std;
struct CQUEUE
{
int Size;
int Front;
int Rear;
int *Arr;
CQUEUE(int s)
{
Size=s; // Size-1 elements will be stored in the circular queue since Front must always be behind Rear
Front=0;
Rear=0;
Arr=new int[Size];
}
bool isEmpty()
{
// this is different from the condition that you used in the other two files where Front did not need to be behind Rear
if(Front==Rear)
return true;
return false;
}
bool isFull()
{
// The space held by Front has to be empty so the circular queue holds Size-1 elements
if( ( (Rear+1)%Size ) == Front )
return true;
return false;
}
void Enqueue(int x)
{
if(isFull()==true)
{
cout<<"The circular queue is full.";
return;
}
Rear=(Rear+1)%Size;
Arr[Rear]=x;
/*
By writing this, you are not changing the value of Rear, only the position after it
Arr[ (Rear+1)%Size ]=x;
Here's why:
num++ and ++num are expressions, num+1 is not
*/
}
int Dequeue()
{
if(isEmpty()==true)
return -1;
// Front is moved forward as the position held by Front is empty.
// The element is held in the position right after it.
Front=(Front+1)%Size;
int res=Arr[Front];
return res;
}
void Display()
{
if(isEmpty()==true)
{
cout<<"The circular queue is empty.";
return;
}
int i;
/*
for( i=Front+1 ; i!=(Rear+1)%Size ; i=(i+1)%Size)
cout<<Arr[i]<<"\t";
*/
i=Front+1;
do
{
cout<<Arr[i]<<"\t";
i=(i+1)%Size;
}
while(i!=( (Rear+1)%Size) ) ;
}
};
int main()
{
int n,i;
cout<<"\nEnter the size of the queue: ";
cin>>n;
CQUEUE q(n);
cout<<"\n\nDisplaying the queue:\n";
q.Display();
cout<<"\n\nPushing elements into the queue:\n";
for(i=1;i<=n-1;i++)
{
cout<<"\nPushing "<<i<<" into the queue";
q.Enqueue(i);
}
cout<<"\n\nDisplaying the queue:\n";
q.Display();
cout<<"\n\nPopping elements from the queue:\n";
for(i=1;i<=n-1;i++)
cout<<"\nPopping "<<q.Dequeue()<<" from the stack.";
cout<<"\n\nDisplaying the queue:\n";
q.Display();
cout<<"\n";
return 0;
}