如何解决环形队列总是要浪费一个位置的问题?

/*如何解决环形队列始终要浪费一个位置的问题?
1.首先我们知道这个空着的位置是用来干嘛的,
队列有两个指针,一个指向队列头front,一个指向队列尾rear,
每次增加一个队列元素:rear+1; 每次出队一个元素:front+1.
所以队列的长度大小就是rear-front. 
2.但是在循环队列中,如果还是用rear-front,就会有一个问题出现,
当两个指针指向同一个位置的时候,我们无法判断到底是队空还是队满。
3.所以,我们可以另外设置一个tag值,用tag值来判断队空和队满.
4.当rear指针指向的下一个位置不为空时,插入数据,再令tag值为1,即判断为队满。 
*/ 
//circular Queue 循环队列实现

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

#define MAXSIZE 3 
typedef int ElemType ;

typedef struct  
{
    
    
	ElemType *base; //存储内存分配基地址
	int front;      //队列头索引
	int rear;       //队列尾索引
}circularQueue;

static int tag = 0;

//判断队列是否还有空位置
void isEmpty(circularQueue *q,ElemType e){
    
    

		if((q->rear+1)%MAXSIZE == q->front){
    
    
		q->base[q->rear]=e;
		tag=1;
		} 
	else{
    
    
		q->base[q->rear]=e;
	}
	
}

//初始化队列
void InitQueue(circularQueue *q)
{
    
    
	q->base = (ElemType *)malloc((MAXSIZE) * sizeof(ElemType));
	if (!q->base) exit(0);
	q->front = q->rear = 0;
}
 
//入队列操作
void InsertQueue(circularQueue *q, ElemType e)
{
    
    
	
//	if ((q->rear + 1) % MAXSIZE == q->front) return; //队列已满时,不执行入队操作
//	q->base[q->rear] = e;  //将元素放入队列尾部
	
	isEmpty(q,e);
	if(tag==1){
    
    	
		printf("队列已满,这是最后插入的一个元素!\n");
	}
	q->rear = (q->rear + 1) % MAXSIZE; //尾部元素指向下一个空间位置,取模运算保证了索引不越界(余数一定小于除数)
}
 
//出队列操作
bool DeleteQueue(circularQueue *q, ElemType *e)
{
    
    
	if (q->front == q->rear){
    
    /* 队列空的判断 */
		return false;
	}
  	else{
    
    
  		*e = q->base[q->front];//将队头元素赋给e
		q->front = (q->front + 1) % MAXSIZE;/* front指针向后移一位置 */
 		return true;
		}
 	
}

//展示队列元素
void ShowQueue(circularQueue *q){
    
    
	int i;
 	i = q->front;
 	do{
    
    
 		printf("%d ",q->base[i]);//访问输出
  		i = (i + 1) % MAXSIZE;//下标i每次加一
	 }
 	while (i != q->rear);
 	printf("\n");
} 

int main()
{
    
    
	circularQueue que;
	InitQueue(&que);
	int elem;
	bool flag = true;
	while(flag)
	{
    
    
		int choice;
		printf("1 :入队, 2:出队, 3:遍历,4:退出\r\n请输入您的选择:");
		scanf("%d",&choice);
		switch((choice))
		{
    
    
			case 1:
				if(tag == 0){
    
    
				printf("输入一个元素:");
				scanf("%d",&elem);
				InsertQueue(&que,elem);	
				}else{
    
    
					printf("队列已满,无法再插入!\n"); 
				}
				
				break;
			case 2:
				;
				if(DeleteQueue(&que,&elem) == 1){
    
    
					printf("出队头元素为:%d\n",elem);
					ShowQueue(&que);	
				}	
				break;
			case 3:
				ShowQueue(&que);
				break; 
			case 4:
				flag = false;
				break;
			default:
				printf("输入错误!\n");
				break;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Zheng_lan/article/details/109019833
今日推荐