常规链队列的实现
1 | #include <iostream> |
循环队列的实现
循环队列主要是针对队列的顺序存储结构,主要目的是避免顺序存储中的内存空间的浪费。 下面的这种方法少用一个储存空间。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#include <iostream>
using namespace std;
#define OK true;
#define ERROR false;
#define MAXSIZE 6
typedef struct Queue{
int *base;
int Front;
int Rear;
}Queue;
bool Init(Queue &Q){
Q.base = (int *)malloc(MAXSIZE * sizeof(int));
if(!Q.base) return ERROR;
Q.Front = Q.Rear = 0;
return OK;
}
//队列长度
int getLength(Queue &Q){
return (Q.Rear - Q.Front + MAXSIZE) % MAXSIZE;
}
bool Insert(Queue &Q , int e){
if((Q.Rear + 1) % MAXSIZE == Q.Front) return ERROR; //队列满的标志
Q.base[Q.Rear] = e;
Q.Rear = (Q.Rear + 1)%MAXSIZE;
return OK;
}
bool Delete(Queue &Q , int &e){
if(Q.Front == Q.Rear) return ERROR; //队列空的标志
e = Q.base[Q.Front];
Q.Front = (Q.Front + 1)%MAXSIZE;
return OK;
}
void print(Queue Q){
if(Q.Front == Q.Rear) cout<<"队列空"<<endl;
else {
while((Q.Front + 1)%MAXSIZE != Q.Rear){
cout<<Q.base[Q.Front]<<' ';
Q.Front = Q.Front+1;
}
cout<<Q.base[Q.Front];
}
cout<<endl;
}
int main()
{
Queue Q;
Init(Q);
for(int i = 0 ; i<5 ; ++i){
int n;
cin>>n;
bool a;
a = Insert(Q , n);
cout<<a<<' ';
}
int e;
cout<<endl;
cout<<getLength(Q)<<endl;
print(Q);
//cout<<Q.Front<<' '<<Q.Rear<<endl;
Delete(Q , e);
cout<<e<<endl;
print(Q);
cout<<getLength(Q)<<endl;
}
