D_S 循环队列的基本操作

//  main.cpp

#include <iostream>

using namespace std;

#include "Status.h"

typedef int QElemType;

#include "SqQueue.h"

int main()

{

    SqQueue Q;

    QElemType e;

    InitQueue(Q);

    EnQueue(Q,1);

    EnQueue(Q,3);

    EnQueue(Q,5);

    EnQueue(Q,7);

    cout<<" 队头元素为:"<<GetHead(Q,e)<<endl;

    cout<<" 队列中从队头至队尾的元素为:";

    QueueTraverse(Q);

    cout<<" 队列的长度为:"<<QueueLength(Q)<<endl;

    DeQueue(Q,e);

    cout<<" 出队的元素为:"<<e<<endl;

    cout<<" 出队操作完成之后队列中从队头至队尾的元素为:";

    QueueTraverse(Q);

    cout<<" 队列的长度为:"<<QueueLength(Q)<<endl;

    return 0;

}

//  Status.h

#ifndef yuan_Status_h

#define yuan_Status_h

#define TRUE 1

#define FALSE 0

#define OK 1

#define ERROR 0

#define INFEASIBLE -1

#define OVERFLOW -2

typedef int Status;

#endif

//  SqQueue.h

#ifndef Y_Y_SqQueue_h

#define Y_Y_SqQueue_h

#define MAXQSIZE 100

typedef struct{

    QElemType *base;

    int front;

    int rear;  

}SqQueue;

Status InitQueue(SqQueue &Q)

{

    Q.base=new QElemType[MAXQSIZE];

    if(!Q.base)  exit(OVERFLOW);

    Q.front=Q.rear=0;

    return OK;

}

Status GetHead(SqQueue Q,QElemType e)

{

    e=Q.base[Q.front];

    return e;

}

Status QueueLength(SqQueue Q)

{

    return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;

}

Status EnQueue(SqQueue &Q,QElemType e)

{

    if ((Q.rear+1)%MAXQSIZE==Q.front) return ERROR;  //尾指针在循环意义上加1后等于头指针,表示满队

    Q.base[Q.rear]=e;

    Q.rear=(Q.rear+1)%MAXQSIZE;

    return OK;

}

Status DeQueue(SqQueue &Q,QElemType &e)

{

    if (Q.front==Q.rear) return ERROR;

    e=Q.base[Q.front];

    Q.front=(Q.front+1)%MAXQSIZE;

    return OK;

}

void QueueTraverse(SqQueue Q)

{

    int i;

    i=Q.front;

    while(i!=Q.rear)

    {

        cout<<Q.base[i]<<"  ";

        i=(i+1)%MAXQSIZE;

    }

    cout<<endl;

}

#endif

原文地址:https://www.cnblogs.com/YuanYe1/p/5014704.html