如果允许在循环队列的两端都可以进行插入和删除操作,写出“从队尾删除”和“从队头插入”的算法

#define SIZE 100
typedef struct
{
	int data[SIZE];
	int front;
	int rear;
	int size;
}queue;
//初始化
void queueinit(queue* ps)
{
	ps->front = ps->rear = 0;
	ps->size = 0;
}
//判空
bool Empty(queue* ps)
{
	return ps->size == 0;
}
//队满
bool isFull(queue* ps)
{
	return ps->size == SIZE;
}
//从队尾删除元素
int pop_rear(queue* ps, int* val)
{
	if ((Empty(ps)))//判空 
	{
		printf("队空,无法删除元素\n");
		return -1;
	}
	*val = ps->data[(ps->rear - 1 + SIZE) % SIZE];
	ps->rear = (ps->rear - 1 + SIZE) % SIZE;
	ps->size--;
	return 1;
}
//从队头插入元素
int push_head(queue* ps, int val)
{
	if (isFull(ps))
	{
		printf("队满,无法加入元素\n");
		return -1;
	}
	ps->front = (ps->front - 1 + SIZE) % SIZE;//先定位,再方便等下的插入
	ps->data[ps->front] = val;
	ps->size++;
	return 1;
}
int main()
{
	queue ps;
	queueinit(&ps);
	//测试队头插入数据
	push_head(&ps, 1);
	push_head(&ps, 2);
	push_head(&ps, 3);
	int val;
	while (!Empty(&ps))
	{
		if (pop_rear(&ps, &val))
		{
			printf("%d", val);
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值