循环队列(顺序存储结构)

本文最后更新于:3 个月前

循环队列的定义、特点和完整代码实现。

循环队列(顺序存储结构)

定义

顺序表类型的队列,定义了两个指针,头指针和尾指针。当入队满的时候,每出队一个头指针都要后移,这样到最后就无法入队新元素了,在入队会导致假溢出。为了解决这一问题,入队和出队后,队头队尾对MAXSIZE取模,这样队列就变成了环形,类似于旋转木马,即循环队列,

特点

可以有效的利用资源

基本算法

主要是判断队列是否为空所采取的方法:

  • 牺牲一个存储单元
  • 增加size属性记录元素个数
  • 增加标志位,判断最近的一次操作是入队还是出队(只有入队会导致队满)

完整代码实现

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
#include<iostream>
#include<string>

using namespace std;

/*
循环队列 顺序实现
*/
#define MAXSIZE 2 //队列元素的最大个数

/* 顺序队列存储结构 */
typedef struct
{
int data[MAXSIZE]; //静态数组存放队列元素
int front; //队头指针
int rear; //队尾指针
int size; //队列元素个数
}SqQueue;

//初始化队列
void InitQueue(SqQueue &S)
{
S.front = 0;
S.rear = 0;
S.size = 0;
}

//判断队列是否空
bool QueueEmpty(SqQueue S)
{
if (S.size == 0)
{
return true;
}
else
{
return false;
}
}

//入队列
bool Push(SqQueue& S, int e)
{
if (S.size == MAXSIZE)
{
return false;
}
S.data[S.rear] = e;
S.rear = (S.rear+1)%MAXSIZE;
S.size++;
return true;
}

//出队列
bool Pop(SqQueue& S, int &e)
{
if (S.size == 0)
{
return false;
}
e = S.data[S.front];
S.front=(S.front+1)% MAXSIZE;
S.size--;
return true;
}

//读取队列顶元素
void GetElem(SqQueue S,int &e)
{
if (S.size == 0)
{
return;
}
e = S.data[S.front];
}

int main()
{
SqQueue S;
InitQueue(S);
cout <<"队列是否为空:" << QueueEmpty(S) << endl;
int a1 = 10;
int a2 = 20;
int b;

cout << "入队列:" << Push(S, a1)<< endl;
cout << "入队列:" << Push(S, a2) << endl;
GetElem(S, b);
cout<<"读取队列顶元素:" <<b <<endl;
cout << "队列大小:" << S.size << endl;
cout << "出队列:" << Pop(S, b) << endl;
cout << "出队列:" << Pop(S, b) << endl;
cout << "队列大小:" << S.size << endl;
cout << "队列是否为空:" << QueueEmpty(S) << endl;
cout << "入队列:" << Push(S, a1) << endl;
cout << "入队列:" << Push(S, a2) << endl;
cout << "队列大小:" << S.size << endl;
return 0;
}

循环队列(顺序存储结构)
https://superlovelace.top/2023/10/13/SqQueue/
作者
棱境
发布于
2023年10月13日
更新于
2023年10月31日
许可协议