双端队列

//双端循环队列、数组表示
#include <stdio.h>  
#define QUEUESIZE 8  
typedef char ElemType;
typedef struct DQueue
{
	ElemType queue[QUEUESIZE];
	int end1;	//左端
	int end2;	//右端
}DQueue;


int EnQueue(DQueue *DQ, ElemType e, int tag);		//队列,插入元素,插入标记
int DeQueue(DQueue *DQ, ElemType *e, int tag);		//队列,删除元素(使用的是指针,传值就不能完成输出了),删除标记


int EnQueue(DQueue *DQ, ElemType e, int tag)
{
	switch (tag)
	{
	case 1:	//end1端点
		if (DQ->end1 != DQ->end2)	//队不满
		{
			DQ->queue[DQ->end1] = e;
			if (DQ->end1 == 0)		//入队时end1减到0把end1移动到数组最大位置减1的位置
			{
				DQ->end1 = QUEUESIZE-1;
			}
			DQ->end1 = (DQ->end1 - 1) % QUEUESIZE;		//end1往左移动一个位置
			return 1;
		}
		else
		{
			return 0;
		}
		break;
	case 2:	//end2端点
		if (DQ->end1 != DQ->end2)		//队不满
		{
			DQ->queue[DQ->end2] = e;
			DQ->end2 = (DQ->end2 + 1) % QUEUESIZE;
			return 1;
		}
		else
		{
			return 0;
		}
		break;
	}
	return 0;
}


int DeQueue(DQueue *DQ, ElemType *e, int tag)		
{
	switch (tag)
	{
	case 1:
		if ((DQ->end1 + 1) % QUEUESIZE != DQ->end2)		//队不空
		{
			DQ->end1 = (DQ->end1 + 1) % QUEUESIZE;
			*e = DQ->queue[DQ->end1];
			return 1;
		}
		else
		{
			return 0;
		}
		break;
	case 2:
		if ((DQ->end2 - 1) % QUEUESIZE != DQ->end1)		//队不空
		{
			if (DQ->end2 == 0)		//如果end2减到0则把end2改到数组的最大值减1的位置
			{
				DQ->end2 = QUEUESIZE - 1;	
			}
			DQ->end2 = (DQ->end2 - 1) % QUEUESIZE;
			*e = DQ->queue[DQ->end2];
			return 1;
		}
		else
		{
			return 0;
		}
		break;
	}
	return 0;
}


//利用顺序存储结构实现双端队列的入队和出队操作  
int main( )
{
	DQueue Q;
	char ch;
	Q.end1 = 3;
	Q.end2 = 4;
	if (!EnQueue(&Q, 'a', 1))
	{
		printf("队列已满,不能入队!");
	}
	else
	{
		printf("a左端入队:\n");
	}
	if (!EnQueue(&Q, 'b', 1))
	{
		printf("队列已满,不能入队!");
	}
	else
	{
		printf("b左端入队:\n");
	}
	if (!EnQueue(&Q, 'c', 1))
	{
		printf("队列已满,不能入队!");
	}
	else
	{
		printf("c左端入队:\n");
	}
	if (!EnQueue(&Q, 'd', 1))
	{
		printf("队列已满,不能入队!");
	}
	else
	{
		printf("d右端入队:\n");
	}
	if (!EnQueue(&Q, 'e', 1))
	{
		printf("队列已满,不能入队!");
	}
	else
	{
		printf("e右端入队:\n");
	}
	printf("队列左端出队一次:");
	DeQueue(&Q, &ch, 2);
	printf("%c\n", ch);
	printf("队列左端出队一次:");
	DeQueue(&Q, &ch, 2);
	printf("%c\n", ch);
	printf("队列右端出队一次:");
	DeQueue(&Q, &ch, 2);
	printf("%c\n", ch);
	printf("队列右端出队一次:");
	DeQueue(&Q, &ch, 2);
	printf("%c\n", ch);
	printf("队列右端出队一次:");
	DeQueue(&Q, &ch, 2);
	printf("%c\n", ch);
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值