队列(数组实现)

本文详细介绍了如何使用数组来实现基本的队列数据结构,包括队列的入队和出队操作,以及探讨了数组实现队列的效率和局限性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include<stdlib.h>
#include<stdio.h>
#define MinQueueSize 5
typedef int  ElementType ;
typedef struct QueueRecord
{
    int Capacity;   //域 ,数组最大容量
    int Front;      //头指针
    int Rear;       //尾指针
    int Size;       //数组大小
    ElementType *Array;   //数组
}*Queue;
int IsEmpty(Queue Q);
int IsFull(Queue Q);
Queue CreateQueue(int MaxElements);
void DisposeQueue(Queue Q);
void MakeEmpty(Queue Q);
void EnQueue(ElementType x,Queue Q);  //入对
ElementType Front(Queue Q);
void DeQueue(Queue Q);                //出对
ElementType FrontAndDequeue(Queue Q); //取得头元素并出对

int IsEmpty(Queue Q)  //判断是否为空
{
    return Q->Size==0;
}
int IsFull(Queue Q)
{
    return Q->Size == Q->Capacity;
}
void MakeEmpty(Queue Q) //构造空队列
{
    Q->Size=0;
    Q->Front=1;  //当为空时 Rear=Front-1
    Q->Rear=0;
}
Queue CreateQueue(int MaxElements)
{
    Queue Q;
    if(MaxElements < MinQueueSize)
    {
	printf("Queue Size is too small\n");
	exit(1);
    }
    Q=malloc(sizeof(struct QueueRecord));
    if(Q == NULL)
    {
	printf("Out of space !!!");
	exit(1);
    }
    Q->Array=malloc(sizeof(ElementType)*MaxElements);
    if(Q->Array == NULL)
    {
	printf("Out of space !!!");
	exit(1);
    }
    Q->Capacity=MaxElements;
    MakeEmpty(Q);
    return Q;
}
static int Succ(int Value,Queue Q)  //申请一个数组空间,
{                                   //当数组达到最大时循环
    if(++Value == Q->Capacity)  //达到最大值时尾指针
	Value=0;
    return Value;
}
void EnQueue(ElementType x,Queue Q)
{
    if(IsFull(Q))
    {
	printf("Full Queue \n");
	exit(1);
    }
    Q->Size++;
    Q->Rear=Succ(Q->Rear,Q);
    Q->Array[Q->Rear]=x;
}
void DeQueue(Queue Q)
{
    if(Q == NULL)
    {
	printf("Empty queue \n");
	exit(1);
    }
    else
    {
	Q->Size--;
	Q->Front=Succ(Q->Front,Q);
    }
}
void DisposeQueue(Queue Q)
{
    if(Q!=NULL)
    {
	free(Q->Array);
	free(Q);
    }
}
ElementType Front(Queue Q)
{
    if(!IsEmpty(Q))
    {
	return Q->Array[Q->Front];
    }
    printf("Empty Queue \n");
    return 0;
}
ElementType FrontAndDequeue(Queue Q)
{
    ElementType x=0;
    if(IsEmpty(Q))
    {
	printf("Empty queue \n");
	exit(1);
    }
    else
    {
	Q->Size--;
	x=Q->Array[Q->Front];
	Q->Front=Succ(Q->Front,Q);
    }
    return x;
}
int main()
{
    Queue Q;
    int i;
    Q=CreateQueue(12);
    for(i=0;i<10;i++)
	EnQueue(i,Q);
    while(!IsEmpty(Q))
    {
	printf("%d ",Front(Q));
	DeQueue(Q);
    }
    printf("\n");
    for(i=0;i<10;i+=2)
	EnQueue(i,Q);
    while(!IsEmpty(Q))
    {
	printf("%d ",Front(Q));
	DeQueue(Q);
    }
    printf("\n");
    DisposeQueue(Q);
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值