顺序队列的基本操作

  • Post author:
  • Post category:其他

顺序队列会发生假溢出的情况,具体运行情况请看效果截图,相关代码如下:
一、顺序队列的定义:

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

#define ERROR  0
#define OK     1
#define TRUE   1
#define FALSE  0
#define QUEUESIZE 10


typedef int Status;
typedef int QElemtype;

typedef struct QNode{
	QElemtype *base;
	int front;
	int rear;
}SqQueue; 

二、顺序队列的初始化:

void InitQueue(SqQueue *Q)
{
	Q->base=(QElemtype*)malloc(sizeof(QElemtype)*QUEUESIZE);
	assert(Q->base!=NULL);
	Q->front=Q->rear=0; 
}

三、入队操作:

Status EnQueue(SqQueue *Q,QElemtype e)
{
	if(Q->rear==QUEUESIZE)
	{
		return ERROR;
	}
	Q->base[Q->rear]=e;
	Q->rear++;
	return OK;
}

四、判断队列是否为空:

Status QueueEmpty(SqQueue *Q)
{
	if(Q->front==Q->rear)
	{
		return TRUE;
	}
	return FALSE;
}

五、求队列长度:

Status QueueLength(SqQueue Q)
{
	return Q.rear-Q.front;
}

六、获取队头元素:

Status GetHead(SqQueue *Q,QElemtype *e)
{
	if(Q->front==Q->rear)
	{
		return ERROR;
	}
	*e=Q->base[Q->front];
	return OK;
}

七、销毁队列:

void DestoryQueue(SqQueue *Q)
{
	if(Q->base)      //队列Q存在 
	{
		free(Q->base);
	}
	Q->base=NULL;
	Q->front=Q->rear=0;
}

八、清空队列:

void ClearQueue(SqQueue *Q)
{
	Q->front=Q->rear=0;
}

九、出队操作:

Status DeQueue(SqQueue *Q,QElemtype *e)
{
	if(Q->front==Q->rear)
	{
		return ERROR;
	}
	*e=Q->base[Q->front];
	Q->front++;
	return OK;
}

十、遍历队列:

void QueueTraverse(SqQueue Q,void(*visit)(QElemtype))
{
	int i=Q.front;
	while(i!=Q.rear)
	{
		visit(Q.base[i]);
		i++;
	}
	printf("\n");
} 
void Print(QElemtype e)
{
	printf("%d ",e);
}

十一、主函数:

int main()
{
	QElemtype i,e,d;
	SqQueue Q;
	InitQueue(&Q);
	printf("请输入队列的%d个元素:\n",QUEUESIZE);
	for(i=0;i<QUEUESIZE;i++)
	{
		scanf("%d",&d);
		EnQueue(&Q,d);
	}
	printf("队列的元素为:");
	QueueTraverse(Q,Print);
	printf("队列长度为:%d\n",QueueLength(Q));
	int k=QueueLength(Q);
	printf("连续%d次由对头删除元素,队尾插入元素:\n",k/2);
	for(i=0;i<k/2;i++)
	{
		DeQueue(&Q,&e);
		printf("删除的队列的元素是:%d,请输入插入的元素:",e);
		scanf("%d",&d);
		EnQueue(&Q,d);
	}
	printf("新的队列元素为:\n");
	QueueTraverse(Q,Print);
	
	int n=GetHead(&Q,&e);
	if(n)printf("对头元素为:%d\n",e);
	else {
		printf("队空!\n");	return -1;
	}
	ClearQueue(&Q);
	printf("清空队列后队列是否为空:%d\t(1:为空 ,0:不为空)\n",QueueEmpty(&Q));
	DestoryQueue(&Q);
	printf("销毁队列后:\nQ.base=%u\tQ.front=%d\tQ.rear=%d\t\n",Q.base,Q.front,Q.rear);
	return 0; 
}

十二、运行效果截图:
在这里插入图片描述

如何解决顺序队列假溢出的现象(https://blog.csdn.net/qq_42552533/article/details/86648556)


版权声明:本文为qq_42552533原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。