数据结构之顺序队列

队列操作详解
本文深入讲解了基于数组实现的队列操作,包括初始化、判断空队列、获取队列长度、队头元素读取、队列遍历等功能,并提供了完整的C语言代码实现。
#include <stdio.h> 
#include <malloc.h> 
  
typedef int QElemType; 
typedef int Status; 
#define Ok 1 
#define Error 0 
#define True 1 
#define False 0 
#define MAXQSIZE 100
typedef struct 
{ 
  QElemType front; 
  QElemType rear; 
  int base[MAXQSIZE]; 
}SqQueue; 
 
Status InitQueue(SqQueue &Q)    //初始化队列 
{
	Q.front=Q.rear=0;
	return Ok;
}

int QueueLength(SqQueue Q)     //队列的长度 
{
	return(Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}

Status QueueEmpty(SqQueue &Q)    //判断队列是否为空 
{
	if(Q.front==Q.rear)
	return True;
	else return False;
}

Status DeQueue(SqQueue &Q,QElemType &e)   //出队 
{
	if(QueueEmpty(Q))
	return Error;
	Q.front=(Q.front+1)%MAXQSIZE;
	return Ok;
} 

Status EnQueue(SqQueue &Q,QElemType e)   //入队 
{
	if((Q.rear+1)%MAXQSIZE==Q.front)
	return Error;
	Q.base[Q.rear]=e;
	Q.rear=(Q.rear+1)%MAXQSIZE;
	return Ok;
} 

QElemType GetHead(SqQueue Q)    //返回队头元素 
{
	if(Q.front!=Q.rear)
	return   Q.base[Q.front];
	return Ok;
}

Status QueueTraverse(SqQueue Q)     //遍历队列 
 { 
   QElemType b = Q.front;  
  while(b!=Q.rear) 
  {
 	printf("%d",Q.base[b]);
    b=(b+1)%MAXQSIZE;
  }
  printf("\n"); 
  return Ok; 
 } 
  
int main()
{
	SqQueue Q;
	QElemType e;
	printf("构造一个空队列......\n"); 
	InitQueue(Q);
	int n; 
    printf("请输入入队的个数:"); 
    scanf("%d", &n);
    printf("请输入入队元素:"); 
    while(n--) 
    { 
      int m; 
      scanf("%d", &m); 
      EnQueue(Q,m); 
    } 
    printf("……本队列是为空吗??……\n");
    if (QueueEmpty(Q) )
         printf("YES !!!\n");
    else
         printf("NO !!!\n");
	printf("……输出队头元素……\n");
 	e=GetHead(Q);
 	printf("队头元素是:\n");
    printf("%d\n",e);
 	printf("……队尾插入元素……\n");
    printf("请输入要插入的元素的数值:\n");
    scanf("%d",&e);
    EnQueue(Q,e);
    printf("现在队中的元素是:\n");
    QueueTraverse(Q);
    printf("\n");
    printf("……队头删除元素……\n");
    printf("删除的元素是:\n");
    scanf("%d",&e);
    DeQueue(Q, e);
    printf("现在队中的元素是:\n");
    QueueTraverse(Q);
    printf("\n");
    printf("您已经成功完成所有的功能!!!\n");    
    return 0; 
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流萤数点

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值