Define the circular queue in C language, and use functions to realize the following functions:
{
- Initialize the queue;
- Into the queue operation: to achieve the element into the queue operation;
- Dequeue operation: realize the dequeue operation of elements;
- Empty and full operation of the queue: judge whether a queue is empty or full;
}
Students who are learning the data structure of c language are best not to copy it. It is the most important thing to write their own code through annotations.
Not much to say, directly on the code:
#include<stdio.h>
#define MAXSIZE 6//定义循环队列的最大长度
//定义结构体
typedef struct {
//将结构体改名为queue
int data[MAXSIZE];
int front;//定义头指针
int rear;//定义尾指针
int num;//记录队列内含的数据数量
}queue;
//初始化队列
void initqueue(queue *q) {
q->front = q->rear = q->num = 0;//初始化让队列的前后指针都指向0
}
//判断队列是否为空
int judgeempty(queue *q) {
if (q->front == q->rear)//若前后指针都指向同一个节点,则判断其为空
return 1;
else
return 0;
}
//判断队列是否已满
int judgefull(queue *q) {
if ((q->rear + 1) % MAXSIZE == q->front)//若尾指针+1取余后仍等于头指针,则判断该队列已满
return 1;
else
return 0;
}
//进队运算
int inputqueue(queue *q,int data) {
if (judgefull(q)) {
printf("队列已满,请使用出队运算后重试!");
return 0;
}
q->data[q->rear] = data;//将进队的数据赋值给尾指针所指向的位置,之后让后指针后移一位
q->rear = (q->rear + 1) % MAXSIZE;//这样运算可以达到0-5的数字循环
++q->num;
return 1;
}
//出队运算
int outputqueue(queue *q){
if (judgeempty(q)) {
printf("队列为空,请使用入队运算后重试!\n");
return 0;
}
q->front = (q->front + 1) % MAXSIZE;
--q->num;
return q->data[q->front-1];
}
//输出全部队列元素
int outputall(queue *q) {
int i;
if (judgeempty(q)) {
printf("当前队列为空,请先使用入队运算后重试!\n");
return 0;
}
printf("当前队列内数据为:\n队头-》");
for (i = 0; i < q->num; i++)
printf("[%d]", q->data[q->front+i]);
printf("《-队尾\n\n队列长度为:%d\n\n",q->num);
}
/********************主测试程序********************/
int main()
{
int num, data, i;
queue q;//初始化队列
initqueue(&q);
while (1)
{
printf("\t提示:系统已自动初始化队列\n\n");
printf("\t\t1.进队运算\n\n");
printf("\t\t2.出队运算\n\n");
printf("\t\t3.输出队列中全部数据\n\n");
printf("\t\t4.退出程序\n\n");
A: printf("*********************\n请选择功能项,并按回车执行:");
scanf("%d", &num);
switch (num)
{
case 1: //进队运算
{
printf("请输入要进队的数据个数(最大值为5):\n");
scanf("%d", &num);
printf("请输入要进队的数据(中间用空格分开):");
while (num) {
scanf("%d", &data);
inputqueue(&q, data);
num--;
}
printf("入队操作成功!\n");
outputall(&q);
goto A;
}
case 2://出队运算
{
if (data=outputqueue(&q))
printf("数据[%d]出队成功!\n",data);
outputall(&q);
goto A;
}
case 3://输出队列中全部数据
{
outputall(&q);
goto A;
}
case 4://退出程序
{
system("cls");
printf("******************>>>>退出成功!");
return;
}
}
}
}