标签:Queue QElemType 队列 ---- int MAXSIZE printf front 数据结构
数据结构----队列(数组)
一、头文件
/*
Queue.h使用注意事项:
MAXSIZE-1为队列长度,可根据自己需求修改。默认MAXSIZE为5
QElemType为存储数据类型,可根据自己需求修改。默认为int型
void InitQueue(Queue* Q) 初始化队列
int InsertQueue(Queue* Q, QElemType e) 若队列未满,则插入元素e为Q的新的队尾元素
int DeleteQueue(Queue* Q, QElemType* e) 出队,删除队头的元素,用e返回其值
int QueueLength(Queue* Q) 计算队当前的长度
QElemType GetQueueTop(Queue* Q) 获取队头元素
*/
#ifndef QUEUE_H
#define QUEUE_H
#define MAXSIZE 5 //队列长度为MAXSIZE-1
typedef int QElemType; //QElemType根据实际情况而定,这里是int
//定义队列结构
typedef struct
{
QElemType data[MAXSIZE];
int front; //队头
int rear; //队尾
}Queue;
//初始化队列
void InitQueue(Queue* Q)
{
Q->front = 0;
Q->rear = 0;
}
//若队列未满,则插入元素e为Q的新的队尾元素
int InsertQueue(Queue* Q, QElemType e)
{
if ((Q->rear+1)%MAXSIZE == Q->front) //队满的判断
{
printf("队已满!\n");
return 0;
}
Q->data[Q->rear] = e; //将元素e赋值给队尾
Q->rear = (Q->rear+1)%MAXSIZE; //将rear指针向后移一位
return 1;
}
//出队,删除队头的元素,用e返回其值
int DeleteQueue(Queue* Q, QElemType* e)
{
if (Q->front == Q->rear) //判断队是否为空
{
printf("队已空!\n");
return 0;
}
*e = Q->data[Q->front]; //将队头的元素赋值给e
Q->front = (Q->front+1)%MAXSIZE; //front指针向后移一位
return 1;
}
//计算队当前的长度
int QueueLength(Queue* Q)
{
return (Q->rear + MAXSIZE - Q->front) % MAXSIZE;
}
//获取队头元素
QElemType GetQueueTop(Queue* Q)
{
return Q->data[Q->front];
}
#endif
二、测试代码
#include <stdio.h>
#include <stdlib.h>
#include <Queue.h>
int main()
{
Queue* Q = (Queue*)malloc(sizeof(Queue));
QElemType e;
InitQueue(Q); //初始化队列
InsertQueue(Q, 20); //将元素20插入队列Q中
InsertQueue(Q, 50);
InsertQueue(Q, 30);
printf("此时队列中的元素为:");
printf("%d\t", Q->data[0]);
printf("%d\t", Q->data[1]);
printf("%d\t", Q->data[2]);
DeleteQueue(Q, &e); //删除队头的元素,用e返回其值
printf("\n删除的元素是:%d\n", e);
printf("删除后队中的元素为:");
printf("%d\t", Q->data[1]);
printf("%d\t", Q->data[2]);
printf("\n队头元素是%d", GetQueueTop(Q));
}
标签:Queue,QElemType,队列,----,int,MAXSIZE,printf,front,数据结构 来源: https://blog.csdn.net/qq_41121113/article/details/83050485
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。