循环队列的基本操作

环形队列可以使用数组实现也可以使用循环链表实现

那么怎样判断循环队列的空与满呢?

q->front==q->rear表示循环队列为空,当(q->rear+1)%maxsize==q->front时,表示循环队列已满。

循环队列的基本操作:

初始化循环队列·

入队列

出队列

检查循环队列是否为空

检查循环队列是否为满

获取循环队列队头元素

获取循环队列队尾元素

释放循环队列

#include <stdio.h>
#include "stdbool.h"
#include "malloc.h"
typedef struct {
    int *base;
    int front;
    int rear;
    int capacity;
}CycleQueue;

void CycleQueueInit(CycleQueue* obj,int c)
{
	obj->capacity=c;
	obj->base=(int*)malloc(sizeof(int)*obj->capacity+1);
	obj->front=obj->rear=0; 
}

bool IsEmpty(CycleQueue* obj) 
{
    return obj->rear==obj->front;
}

bool IsFull(CycleQueue* obj) 
{
    return (obj->rear+1)%(obj->capacity+1)==obj->front;

}

bool CycleQueuePush(CycleQueue* obj, int value) {
    if(IsFull(obj))
    {
    	printf("队满");
    	return 0;
	}
    obj->base[obj->rear]=value;
    obj->rear=(obj->rear+1)%(obj->capacity+1);
}

bool CycleQueuePop(CycleQueue* obj) 
{
    if(IsEmpty(obj))
    {
    	printf("队空");
		return 0; 
	}
    obj->front=(obj->front+1)%(obj->capacity+1);
}

void CycleQueueShow(CycleQueue *obj)
{
	for(int i=obj->front;i!=obj->rear;i=(i+1)%(obj->capacity+1))
	printf("%d ",obj->base[i]);
}


int CycleQueueFront(CycleQueue* obj) {
    if(IsEmpty(obj))
    {
    	printf("队空");
		return 0; 
	}
    return obj->base[obj->front];
}

int CycleQueueRear(CycleQueue* obj) {
    if(IsEmpty(obj))
    {
    	printf("队空");
		return 0; 
	}
    return obj->base[(obj->rear-1+obj->capacity+1)%(obj->capacity+1)];
}

void CycleQueueFree(CycleQueue* obj) {
    free(obj->base);
    free(obj);
}

int main()
{
	CycleQueue q;
	CycleQueueInit(&q, 8);
	CycleQueuePush(&q, 1);
	CycleQueuePush(&q, 3);
	CycleQueuePush(&q, 5);
	CycleQueuePush(&q, 7);
	CycleQueuePush(&q, 9);
	CycleQueuePush(&q, 11);
	CycleQueuePush(&q, 13);
	CycleQueuePush(&q, 15);
	CycleQueueShow(&q);
	printf("\n");
	CycleQueuePop(&q);
	CycleQueueShow(&q);
	printf("\n");
	printf("队头元素为:%d\n",CycleQueueFront(&q));
	printf("队尾元素为:%d\n",CycleQueueRear(&q));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值