数据结构循环队列

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
#include<stdio.h>
#include<stdlib.h>
#define OK 1 //通过
#define ERROR 0 //错误
#define OVERFLOW -2 //堆栈溢出
#define MAXSIZE 50 //容量
typedef int Status; //函数类型,其值为状态码
typedef char ElemType; //抽象数据类型
//循环队列
typedef struct
{
ElemType* base;
int front;
int rear;
}SqQueue;
typedef enum
{
f, t
}Bool;
//初始化
Status initQueue(SqQueue* Q)
{
Q->base = new ElemType[MAXSIZE];
if (!Q->base)
{
return OVERFLOW;
}
Q->front = Q->rear = 0;
return OK;
}
//判空
Bool isEmpty(SqQueue* Q)
{
return Q->front == Q->rear ? t : f;
}
//长度
int getLength(SqQueue* Q)
{
return (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
}
//是否满
Bool isFull(SqQueue* Q)
{
return (Q->rear + 1) % MAXSIZE == Q->front ? t : f;
}
//入队
Status enQueue(SqQueue* Q, ElemType e)
{
if (isFull(Q))
{
return ERROR;
}
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXSIZE;
return OK;
}
//出队
ElemType deQueue(SqQueue* Q)
{
if (isEmpty(Q))return ERROR;
ElemType e = Q->base[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return e;
}
//取队头
ElemType getHead(SqQueue* Q)
{
if (!isEmpty(Q))return Q->base[Q->front];
return NULL;
}
int main(void)
{
SqQueue* Q = new SqQueue;
printf("初始化-----------%s\n", initQueue(Q) == OK ? "成功" : "失败");
printf("是否为空----------%s\n", isEmpty(Q) ? "空" : "不空");
char* str = "https://github.com/pengxiandyou";
printf("开始入队\n");
for (int i = 0; i <= _mbstrlen(str) - 1; ++i)
{
printf("入队-----------%s--------长度 %d\n", enQueue(Q, str[i]) == OK ? "成功" : "失败", getLength(Q));
}
printf("是否为空----------%s\n", isEmpty(Q) ? "空" : "不空");
printf("队头为---------%c\n", getHead(Q));
printf("开始出队\n");
for (int i = 31 - 1; i >= 0; --i)
{
printf("%c", deQueue(Q));
}
printf("\n");
system("pause");
return 0;
}