3.3循环队列——队列的顺序表示和实现


#include <iostream>

using namespace std;
// -----循环队列一队列 的顺序存储结构-----
# define MAXQSIZE 100
//最大队列长度
typedef struct
{
    int *base; //初始化的动态分配存储空间
    int front ; //头指针,若队列不空,指向队列头元素
    int rear ; //尾指针,若队列不空,指向队列尾元素的下一个位置
} SqQueue;

// -----循环队列的基本操作的算法描述-----
int InitQueue (SqQueue &Q)//*3.3.1构造一个空队列Q
{
    Q.base = (int*)malloc(MAXQSIZE*sizeof(int));
    if (!Q. base)
        return 0; // 存储分配失败
    Q. front = Q.rear = 0;
    return 1;
}

int QueueLength (SqQueue Q)//返回Q的元素个数,即队列的长度
{
    return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}

int EnQueue (SqQueue &Q, int e)//*3.3.2插入元素e为Q的新的队尾元素
{
    if((Q.rear+ 1)%MAXQSIZE == Q.front)
        return 0; //队列满
    Q.base[Q. rear] = e;
    Q.rear = (Q.rear+ 1)%MAXQSIZE;
    return 1;
}
int DeQueue (SqQueue &Q, int &e)//*3.3.3若队列不空,则删除Q的队头元素,用e返回其值,并返回OK;
//否则返回ERROR
{
    if (Q. front == Q. rear)
        return 0;
    e = Q. base[Q. front];
    Q. front = (Q. front+ 1)%MAXQSIZE;
    return 1;
}

int main()
{
    SqQueue Q;
    InitQueue(Q);
    for(int i=0; i<10; i++)
    {
        EnQueue(Q, i);
    }
    int len = QueueLength(Q);
    printf("len = %d\n", len);
    for(int i=0; i<5; i++)
    {
        int e;
        DeQueue(Q, e);
        printf("e = %d\n", e);
    }
    len = QueueLength(Q);
    printf("len = %d\n", len);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42137874/article/details/107719517