数据结构学习之路(四)用数组简单实现循环队列

若有写的不妥的地方,留言或在通过文章下方邮箱联系我即可,万分感谢。

我是在mac系统下调试的代码,需要include的包可能会与其他系统略有不同。


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

typedef struct Queue{
	int *pBase;
	int front;
	int rear;
}*PQUEUE, QUEUE;

void init(PQUEUE);

void showQueue(PQUEUE);

bool isFull(PQUEUE);

bool isEmpty(PQUEUE);

bool in_queue(PQUEUE, int);

bool out_queue(PQUEUE, int *);

int main(void){
	PQUEUE pQueue;
	init(pQueue);
	in_queue(pQueue,1);
	in_queue(pQueue,2);

	showQueue(pQueue);
	int val;
	out_queue(pQueue, &val);
	printf("%d\n", val);
	out_queue(pQueue, &val);
	printf("%d\n", val);
	out_queue(pQueue, &val);
	printf("%d\n", val);

	return 0;
}

void init(PQUEUE pQueue){
	pQueue->pBase = (int *)malloc(sizeof(int) * 10);
	if(pQueue->pBase==NULL){
		printf("%s\n", "内存分配失败!");
		exit(-1);
	}

	pQueue->front = 0;
	pQueue->rear = 0;
}

bool in_queue(PQUEUE pQueue, int val){

	if (isFull(pQueue))
	{
		printf("%s\n", "栈已满!");
		return false;
	}

	pQueue->pBase[pQueue->rear] = val;
	pQueue->rear = (pQueue->rear+1)%10;

	return true;
}

bool out_queue(PQUEUE pQueue, int * pVal){
	if (isEmpty(pQueue)){
		printf("%s\n", "栈已空!");
		return false;
	}

	* pVal = pQueue->pBase[pQueue->front];
	pQueue->front = (pQueue->front+1)%10;
	return true;

}

bool isFull(PQUEUE pQueue){
	if ( (pQueue->rear+1)%10 == pQueue->front )
		return true;
	return false;
}

bool isEmpty(PQUEUE pQueue){
	if(pQueue->front == pQueue->rear)
		return  true;
	return false;
}


void showQueue(PQUEUE pQueue){
	int i = pQueue->front;
	while(i != pQueue->rear){
		printf("%d  ", pQueue->pBase[i]);
		i = (i+1)%10;
	}
	printf("\n");
}


email: 17126252@bjtu.edu.cn

版权声明:博客编写不易,转载时请注明出处,万分感谢 !

https://blog.csdn.net/zyy_2018/article/details/79772177


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值