第三章(4).循环队列

来源:互联网 发布:异星工厂电路网络 编辑:程序博客网 时间:2024/06/18 06:09

#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
原创粉丝点击