队列的顺序存储结构和操作实现

#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
typedef int ElemType;
typedef struct SequQueue
{
	ElemType *queue;
	int front, rear;
	int MaxSize;
}Queue;
//队列 front指向的为空,即Q->queue[Q->fornt+1]才为队首元素,以便判别队列是否满与空
/******************************************/
//初始化队列
/******************************************/
void initQueue(Queue* Q, int ms)
{
	if (ms <= 10)
	{
		Q->MaxSize = 10;
	}
	else
	{
		Q->MaxSize = ms;
	}
	Q->queue = calloc(Q->MaxSize, sizeof(ElemType));
	if (!Q->queue)
	{
		printf("分配内存失败!\n");
		exit(1);
	}
	Q->front = Q->rear = 0;
}
/***********************************************************/
//向队列插入元素,若队列已满需重新分配更大内存空间
void enQueue(Queue* Q, ElemType item)
{
	if ((Q->rear + 1) % Q->MaxSize == Q->front)//扩大内存
	{
		int i;
		Q->queue = realloc(Q->queue, 2 * sizeof(ElemType) * Q->MaxSize);
		if (!Q->queue)
		{
			printf("申请内存失败!,exit\n");
			exit(1);
		}
		for (i = 0; i <= Q->rear; i++)//把在front前面的元素后移
		{
			Q->queue[Q->MaxSize + i] = Q->queue[i];
		}
		Q->rear = Q->rear + Q->MaxSize;//更新rear
		Q->MaxSize = Q->MaxSize * 2;//更新MaxSize
	}
	Q->rear = (Q->rear + 1) % Q->MaxSize;
	Q->queue[Q->rear] = item;
}
/*************************************************************/
//从队列中删除元素并返回
ElemType outQueue(Queue* Q)
{
	if (Q->front == Q->rear)//检查队列是否为空
	{
		printf("队列为空,退出!\n");
		exit(1);
	}
	Q->front = (Q->front + 1) % Q->MaxSize;
	return Q->queue[Q->front];//删除的元素
}
/*************************************************************/
//读取队首元素,不改变队列状态
ElemType peekQueue(Queue* Q)
{
	if (Q->front == Q->rear)
	{
		printf("队列为空!,退出!");
		exit(1);
	}
	return Q->queue[(Q->front + 1) % Q->MaxSize];
}
/*****************************************************************/
//检查一个队列是否为空,若是则返回1,否则而返回0
int emptyQueue(Queue* Q)
{
	return Q->front == Q->rear;
}
/****************************************************************/
//清楚出一个队列为空,并释放动态空间
void clearQueue(Queue* Q)
{
	if (Q->queue != NULL)
	{
		free(Q->queue);
		Q->queue = NULL;
		Q->front = Q->rear = 0;
		Q->MaxSize = 0;
	}
}
/****************************************************************/
#endif

#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
int main()
{
	int i, x = 12;
	Queue q;
	Queue* Q=&q;
	initQueue(Q,1);
	enQueue(Q, 35);
	enQueue(Q, 2 * x + 3);
	enQueue(Q, -16);
	printf("%d ", peekQueue(Q));
	printf("%d\n", outQueue(Q));
	for (i = 0; i < 30; i += 2)
	{
		enQueue(Q, i);
	}
	while (!emptyQueue(Q))
	{
		printf("%d ",outQueue(Q));
	}
	printf("\n");
	clearQueue(Q);

	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值