循环队列基本操作

/*
 * 循环队列基本操作。
 * 少用一个元素空间,约定以“队列头指针在队列尾指针的下一个位置”作为队列满的标志。
 * “队列头指针等于队列尾指针”作为队列空的标志。
 */
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>

#define MAXQSIZE 100
typedef char ElemType;
typedef struct
{
	ElemType *base;
	int front;
	int rear;
} Queue;

bool InitQueue(Queue *queue);
int QueueLength(Queue queue);
bool EnQueue(Queue *queue, ElemType e);
bool DeQueue(Queue *queue, ElemType *e);

int main()
{
	Queue queue;
	ElemType elem[26],temp;
	int i,length;

	InitQueue(&queue);
	for (i = 0; i < 26; i++)
	{
		elem[i] = 'A'+i;
		EnQueue(&queue, elem[i]);
	}
	length = QueueLength(queue);
	printf("length:%d\n", length);
	for (i = 0; i < length; i++)
	{
		DeQueue(&queue, &temp);
		putchar(temp);
	}
	return 0;
}

//构造空队列。
bool InitQueue(Queue *queue)
{
	queue->base = (ElemType*)malloc(sizeof(ElemType)*MAXQSIZE);
	if (!queue->base) return false;
	queue->front = queue->rear = 0;
	return true;
}

//求队列长度。
int QueueLength(Queue queue)
{
	return (queue.rear - queue.front + MAXQSIZE) % MAXQSIZE;
}

//插入元素e为队列的队尾元素。
bool EnQueue(Queue *queue, ElemType e)
{
	if ((queue->rear + 1) % MAXQSIZE == queue->front)	//队列满
		return false;
	queue->base[queue->rear] = e;
	queue->rear = (queue->rear + 1) % MAXQSIZE;
	return true;
}

//删除队列的队头元素,用e返回其值。
bool DeQueue(Queue *queue, ElemType *e)
{
	if (queue->front == queue->rear)	//队列空
		return false;
	*e = queue->base[queue->front];
	queue->front = (queue->front + 1) % MAXQSIZE;
	return true;
}

转载于:https://www.cnblogs.com/Camilo/p/3896768.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值