-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircular Queue.cpp
More file actions
100 lines (97 loc) · 2.09 KB
/
Circular Queue.cpp
File metadata and controls
100 lines (97 loc) · 2.09 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
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iostream>
#include<iomanip>
using namespace std;
class CRingQueue {
private:
int iLen;
int iSize;
int iFront;
int iRear;
int* pArr;
public:
CRingQueue(int size) {//创建队列
iSize = size;
iFront = iRear = iLen = 0;
pArr = new int[size];
}
~CRingQueue() { free(pArr); pArr = NULL; }/*删除队列*///队头队尾操作
void QueueRearInc() { iRear++; iRear = iRear % iSize; }
void QueueFrontInc() { iFront++; iFront = iFront % iSize; }
bool IsEmpty() { return (iLen == 0); }/*队列判空*/
bool IsFull() { return (iLen >= iSize); }/*队列判满*/
int Size() { return iLen; }/*返回队列现有长度*/
//往队尾放入元素
bool EnQueue(int element) {
if (IsFull()) {
cout << "Error : OverFlow !" << endl;
return false;
}
pArr[iRear] = element; QueueRearInc(); iLen++;
return true;
}
int Front() {
if (IsEmpty()) return 0x80000000;
return pArr[iFront];
}
int Rear() {
if (IsEmpty()) return 0x7FFFFFFF;
return pArr[iRear];
}
//删除队列第一个元素
bool DeQueue(int& element) {
if (IsEmpty()) {
cout << "Error : UnderFlow" << endl;
return false;
}
element = pArr[iFront];
QueueFrontInc();
iLen--;
return true;
}
//打印队列中的全部元素
void Disp() {
if (!IsEmpty()) cout << "Head : " << Front() << ", Tail : " << Rear() << endl;
int iHead = iFront;
for (int i = 0; i < iLen; i++) {
cout << setw(4) << pArr[iHead++ % iSize];
}
cout << endl;
}
};
CRingQueue Producer(int* items, int len)
{
CRingQueue target(len);
for (int i = 0; i < len; i++)
{
target.EnQueue(items[i]);
target.Disp();
}
return target;
}
void Consumer(CRingQueue target)
{
while (!target.IsEmpty())
{
int ele = 1;
target.DeQueue(ele);
target.Disp();
}
}
int main()
{
int len;
cout << "Please input the capacity" << endl;
cin >> len;
int* items = new int[len];
cout << "Please input the elements" << endl;
for (int i = 0; i < len; i++)
{
cin >> items[i];
}
CRingQueue target = Producer(items, 5);
Consumer(target);
return 0;
}