【自己动手写数据结构】 -- 循环队列的表示与实现



/*
 * 循环队列的表示与实现
 * 说明:循环队列是队列的一种顺序存储表示,和顺序栈类似
 */

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

/*
 * 自定义布尔类型
 */
typedef int BOOL;
#define TRUE 1
#define FALSE 0

const int MAXSIZE = 100;

typedef int datatype;
typedef struct {
	datatype *base;//存储区首地址
	int front;//头指针
	int rear;//尾指针
}SQueue;

/*
 * 循环队列的初始化
 */
void initQueue(SQueue *squeue) {
	squeue->base = (datatype*) malloc(MAXSIZE*sizeof(datatype));
	if(squeue->base == NULL) {
		printf("分配失败!");
		exit(1);
	}
	squeue->front = squeue->rear = 0;
}

/*
 * 往循环队列中插入新结点
 */
BOOL enQueue(SQueue *squeue, datatype elem) {
	//判断该队列是否满了
	if((squeue->rear+1)%MAXSIZE == squeue->front) {
		printf("队列已满\n");
		return FALSE;
	}
	//往队列中插入元素
	squeue->base[squeue->rear] = elem;
	squeue->rear = (squeue->rear+1) % MAXSIZE;
	return TRUE;
}

/*
 * 循环队列删除元素
 */
BOOL deQueue(SQueue *squeue, datatype *elem) {
	//判断队列是否为空
	if(squeue->front == squeue->rear) {
		printf("队列已空!\n");
		return FALSE;
	}
	*elem = squeue->base[squeue->front];
	squeue->front = (squeue->front+1) % MAXSIZE;
	return TRUE;
}

/*
 * 打印队列中的元素
 */
void printQueue(SQueue *squeue) {
	int index = squeue->front;
	while(index != squeue->rear) {
		printf("%d ", squeue->base[index]);
		index = (index+1) % MAXSIZE;
	}
}

int main(void) {
	SQueue sq;
	initQueue(&sq);
	for(int i = 0; i < 10; i++) {
		enQueue(&sq, i);
	}
	printQueue(&sq);
	printf("\n");
	for(int i = 0; i < 10; i++) {
		deQueue(&sq, &i);
		printf("%d ", i);
		printQueue(&sq);
		printf("\n");
	}
}







 








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值