第三章(4).循环队列

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

#define MAXSIZE 10

typedef int QElemType;

typedef struct
{
 QElemType *base;   //初始化的动态分配空间,可以想象为一段数组空间
 int front;         //头指针,若队列不空,则指向队列头元素
 int rear;          //尾指针,若队列不空,则指向队列尾元素的下一位置
}SqQueue;

void InitQueue(SqQueue *Q)
{
 Q->base = (QElemType *)malloc(MAXSIZE*sizeof(QElemType)); 
 if(!Q->base)    //存储分配失败
 {
  exit(0);
 }
 Q->front = Q->rear = 0;    //为方便起见
}

void EnQueue(SqQueue *Q,QElemType e)  
{
 if((Q->rear + 1)%MAXSIZE == Q->front)  //队列满
 {
  exit(0);
 }
 Q->base[Q->rear] = e;
 Q->rear = (Q->rear + 1)%MAXSIZE;   //尾指针增1,(%MAXSIZE)因为头指针也会向后退
}
//判定队列空间满:其一是另设一个标志位以区别队列是空还是满,
//其二是少用一个元素空间,约定以“队列头指针在队列尾指针的下一位置上”作为队列呈满状态的标志

void DeQueue(SqQueue *Q,QElemType *e)  
{
 if(Q->front == Q->rear)    //空队列
 {
  exit(0);
 }
 *e = Q->base[Q->front];
 Q->front = (Q->front + 1)%MAXSIZE;   //头指针增1
}

int QueueLength(SqQueue Q)
{
 return (Q.rear - Q.front + MAXSIZE)%MAXSIZE;   //(Q.rear - Q.front ) < MAXSIZE , (恒小于)
}

int QueueEmpty(SqQueue Q)
{
 if(QueueLength(Q) == 0)
 {
  return 1;
 }
 return 0;
}

void PrintQueue(SqQueue Q)
{
 int i;
 for( i = 0; i < QueueLength(Q) ; i++)
 {
  printf("%d ",Q.base[Q.front + i]);
 }
 printf("\n");
}

void main(void)
{
 SqQueue *Q;

 Q = NULL;
 Q = (SqQueue *)malloc(sizeof(SqQueue));

 InitQueue(Q);
 EnQueue(Q,3);
 EnQueue(Q,4);
 EnQueue(Q,5);
 EnQueue(Q,6);
    EnQueue(Q,7);

 PrintQueue(*Q);

 printf("%d\n",QueueLength(*Q));
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值