数据结构-循环队列-队列的顺序表示和实现

思想:用一组地址连续的存储单元依次存放队列头和队列尾的元素,另外需要两个指针front和rear分别表示队列头和队列尾的位置

/*循环队列的的顺序表示和实现*//*
*设置队头指针front 和队尾指针  rear
* 约定初始队列的时候,front=rear=0
*头指针始终指向队头元素,尾指针指向队列尾元素的下一个位置
*/

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

#define  MAX_SIZE   100
#define  INCREMENT  10
#define  OK         1
#define  ERROR      0

#define  QElemType  int
#define  Status     int


//顺序队列结构
typedef  struct  {
    QElemType  front;//队列头指针
    QElemType  rear;//队列尾指针
    QElemType  *base;//指向队列基址
}SqQueue;



//初始化一个队列
Status  InitQueue(SqQueue *S)
{
    S->base=(QElemType *)malloc(sizeof(QElemType)*MAX_SIZE);
    if(!S->base)
    {
        printf("内存分配出错,初始化队列失败\n");
        return ERROR;
    }
    S->front=S->rear=0;
    return OK;
}


//销毁一个队列
Status  DestroyQueue(SqQueue  *S)
{
    free(S->base);
    return OK;
}


//返回一个队列的长度
Status  QueueLength(SqQueue  *S)
{
    //循环队列
    return  (S->rear-S->front+MAX_SIZE)%MAX_SIZE;
}



//向队列中插入一个元素e,作为新的队尾元素
//必须留一个空位置用来判断队列是否为满的情况
Status  EnQueue(SqQueue *S,QElemType e)
{
    /*if(S->front==S->rear)//如果队列中没有元素
    {
        *base=e;
        S->rear+=1;
    }*/
    if((S->rear+1)%MAX_SIZE==S->front)//如果队列为满的话
    {
        printf("队列为满,不能再插入元素\n");
        return ERROR;
    }
    *(S->base+S->rear)=e;
    S->rear=(S->rear+1)%MAX_SIZE;
    return OK;

}


//从队列中队头处删除一个元素
Status DeQueue(SqQueue *S,QElemType *e)
{
    //如果队列为空队列的话
    if(S->front==S->rear)
    {
        printf("队列为空\n");
        return ERROR;
    }
    *e=S->base[S->front];
    S->front=(S->front+1)%MAX_SIZE;
    return OK;
}


//遍历打印输出队列
void  PrintQueue(SqQueue *S)
{
    if(S->front==S->rear)
        printf("队列为空\n");
    //int n=QueueLength(S);
    int num=S->front;
    while(((num+MAX_SIZE)%MAX_SIZE)!=S->rear)
    {
        printf("%d ",(S->base)[num]);
        num=(num+1+MAX_SIZE)%MAX_SIZE;
    }
    printf("\n");

}




int main()
{
    SqQueue *S=(SqQueue *)malloc(sizeof(SqQueue));
    InitQueue(S);


    QElemType i;
    for(i=0;i<20;i++)
        EnQueue(S,i);
    PrintQueue(S);
    int n;
    n=QueueLength(S);
    printf("队列长度为:%d\n",n);

    QElemType *p=(QElemType*)malloc(sizeof(QElemType));
    DeQueue(S,p);
    printf("%d\n",*p);
    DeQueue(S,p);
    printf("%d\n",*p);
    DeQueue(S,p);
    printf("%d\n",*p);

    n=QueueLength(S);
    printf("队列长度为:%d\n",n);

    return 0;
}

运行结果如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值