其他分享
首页 > 其他分享> > 数据结构----队列(数组)

数据结构----队列(数组)

作者:互联网

数据结构----队列(数组)

一、头文件

/*
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