数据结构C/C++语言 循环队列基本操作代码

实现循环队列的基本操作:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

#define MAXQSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define False 0
#define True 1

typedef int Status;
typedef int QElemType;
typedef struct
{
    QElemType *base;    //存储空间的基地址
    int front;      //头指针
    int rear;       //尾指针
}SqQueue;

//循环队列的初始化
Status InitQueue(SqQueue &q)
{
    q.base = new QElemType[MAXQSIZE];   //为队列分配一个最大容量为 MAXQSIZE 的数组空间
    if(!q.base) exit(OVERFLOW);     //存储分配失败
    q.front = q.rear = 0;       //头指针和尾指针置为零,队列为空
    return OK;
}

//求循环队列的长度
int QueueLength(SqQueue q)
{
    //return (q.rear-q.front+MAXQSIZE)%MAXQSIZE;  //返回Q的元素个数,即队列长度
    cout<<(q.rear-q.front+MAXQSIZE)%MAXQSIZE<<'\t';
    return OK;
}

//入队
Status EnQueue(SqQueue &q,QElemType e)//插入元素 e 为Q的新的队尾元素
{
    if((q.rear+1)%MAXQSIZE==q.front)    //尾指针在循环意义上加1后等于头指针,表明队满
        return ERROR;
    q.base[q.rear]=e;   //新元素插入队尾
    q.rear=(q.rear+1)%MAXQSIZE; //队尾指针加1
    return OK;
}

//出队
Status DeQueue(SqQueue &q,QElemType &e)//删除 q 的队头元素,用 e 返回其值
{
    if(q.front==q.rear) return ERROR;//队空
    e=q.base[q.front];      //保存队头元素
    q.front=(q.front+1)%MAXQSIZE;//队头指针加1
    return OK;
}
//取队头元素
QElemType GetHead(SqQueue q)//返回  的队头元素,不修改队头指针
{
    if(q.front!=q.rear)     //队列非空
        //return q.base[q.front];//返回队头元素的值,队头指针不变
        cout<<q.base[q.front]<<endl;
        return OK;
}

bool FullQueue(SqQueue &q)
{
    if(q.rear==(q.front+1)%MAXQSIZE)
    {
        return 1;
    }
    else  return 0;
}

bool EmptyQueue(SqQueue &q)
{
    if(q.front==q.rear)
        return 1;
    else  return 0;
}

//遍历队列
Status SqQueueTraver(SqQueue q,Status(*visit)(QElemType))
{
    QElemType *b=&q.front;
    QElemType *t=&q.rear-1;
    while(b<t)
        visit(*b++);
    return OK;
}

Status visit(QElemType c)
{
    cout<<c<<endl;
    return OK;
}
int main()
{
    QElemType e;
    SqQueue q;
    InitQueue(q);
    int a;
    cout<<"请输入要入队的元素个数:"<<endl;
    cin>>a;
    //if(a>MAXQSIZE) cout<<"输入范围过大!"<<endl;
        while(a--)
    {
        int n;
        cin>>n;
        EnQueue(q,n);
    }
    cout<<"当前队列中的元素有"<<'\t';
    QueueLength(q);
    cout<<"个"<<endl;
    cout<<"输出队头元素:"<<endl;
    GetHead(q);
    cout<<"删除队头元素"<<endl;
    DeQueue(q,e);
    if(FullQueue(q)) cout<<"队列已满"<<endl;
    if(EmptyQueue(q)) cout<<"队列为空"<<endl;
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/baidu_41774120/article/details/82958733