您的位置:首页 > 编程语言 > C语言/C++

使用数组实现队列(C语言)

2017-09-05 20:24 691 查看


队列结构体定义

#define QueueSize 40 // 队伍容量

typedef struct{
DataType queue[QueueSize];// 用于保存类型为DataType队列元素的数组
int front,rear;// 用于保存队头和队尾下标信息
}SeqQueue;
1
2
3
4
5
6
1
2
3
4
5
6


实现算法

实现算法存放在Queue.h头文件中

// 初始化队列
void InitQueue(SeqQueue *SQ){
SQ->front = SQ->rear = 0;
}

// 判断队列是否为空
int QueueEmpty(SeqQueue SQ){
// 队头坐标与队尾坐标相等时,即为空队列
if(SQ.front == SQ.rear){
return 1;
}else{
return 0;
}
}

// 入队操作
int EnterQueue(SeqQueue *SQ,DataType e){
// 边界判断,假如队列满了不能入队
if(SQ->rear == QueueSize){
printf("队列已满,不能入队.\n");
return 0;
}
// 新元素入队,需要将队尾指针往后移动
SQ->queue[SQ->rear++] = e;
return 1;
}

// 出队操作
int DeleteQueue(SeqQueue *SQ,DataType *e){
// 边界判断,假如队列空了不能出队
if(SQ->front == SQ->rear){
printf("队列已空,不能出队.\n");
return 0;
}
// 元素出队,需要将队头指针往后移动
*e = SQ->queue[SQ->front++];
return 1;
}
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
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


测试实例

#include <stdio.h>
#define QueueSize 40
// 定义队列结构体
typedef char DataType;
typedef struct{
DataType queue[QueueSize];
int front,rear;
}SeqQueue;
// 必须放在定义队列结构体之后
#include "SeqQueue.h"

int main(void){
SeqQueue SQ;
char str[] = {"1234567"};
int i,length = 8;
char x;
InitQueue(&SQ);
for(i=0;i<length;i++){
EnterQueue(&SQ,str[i]);
}
printf("顺序队列中的元素为:");
if(!QueueEmpty(SQ)){
for(i=SQ.front;i<SQ.rear;i++){
printf("%c",SQ.queue[i]);
}

}

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: