数据结构(8)----栈与队列之循环队列

循环队列的使用

循环队列顺序存储结构

#define MAXSIZE 100
typedef int QElemType;
typedef struct SqQueue{
    QElemType data[MAXSIZE];
    int front;/*指向队列头*/
    int rear;/*指向队列尾*/
};

 循环队列为空的判断:Q->front == Q->rear

循环队列队满的判断:(Q->rear + 1) % MAXSIZE == Q->front

队满入下图所示:

计算队列长度公式:(rear-front+QueueSize)%QueueSize

 

#include<iostream>
using namespace std;
#define MAXSIZE 100
typedef int QElemType;
typedef struct SqQueue{
    QElemType data[MAXSIZE];
    int front;/*指向队列头*/
    int rear;/*指向队列尾*/
};
/*初始化队列*/
void InitQueue(SqQueue *Q){
    Q->front = 0;
    Q->rear = 0;
}
/*求队列长度*/
int QueueLength(SqQueue Q){
    return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}
/*入队操作*/
void EnQueue(SqQueue *Q, QElemType e){
    if ((Q->rear + 1) % MAXSIZE == Q->front){
        cout << "该队列已满" << endl;
        return;
    }
    Q->data[Q->rear] = e;
    Q->rear = (Q->rear + 1) % MAXSIZE;
}
/*出队操作*/
void DeQueue(SqQueue *Q){
    if (Q->front == Q->rear){
        cout << "该对列已空" << endl;
        return;
    }
    cout << Q->data[Q->front] << endl;
    Q->front = (Q->front + 1) % MAXSIZE;
}

int main(){
    SqQueue Q;
    InitQueue(&Q);
    EnQueue(&Q, 3);
    EnQueue(&Q, 2);
    EnQueue(&Q, 3);
    EnQueue(&Q, 4);
    EnQueue(&Q, 5);
    DeQueue(&Q);
    DeQueue(&Q);
    DeQueue(&Q);
    DeQueue(&Q);
    cout << QueueLength(Q) << endl;
}

 附:队列的链式存储结构代码示例:

#include<iostream>
using namespace std;

typedef int QElemType;

typedef struct QNode{
    QElemType data;
    struct QNode *next;
};
typedef struct LinkQueue{
    QNode * front, *rear;
};
/*初始化队列*/
void InitQueue(LinkQueue *Q){
    QNode *q = new QNode;
    q->data = 0;
    q->next = NULL;
    Q->front = q;
    Q->rear = q;
}
/*入队*/
void EnQueue(LinkQueue *Q, QElemType e){
    QNode *p = new QNode; 
    p->data = e;
    p->next = NULL;
    Q->rear->next = p; //队列头指针指向空节点
    Q->rear = p;
}
/*出队*/
void DeQueue(LinkQueue *Q){
    QNode *p;
    if (Q->front == Q->rear){
        cout << "该队列已空" << endl;
        return;
    }
    p = Q->front->next;
    cout << p->data<<endl;
    Q->front->next = p->next;
    if (Q->rear == p){
        Q->rear = Q->front;
    }
    free(p);
}


int main(){
    LinkQueue Q;
    InitQueue(&Q);
    EnQueue(&Q, 1);
    EnQueue(&Q, 2);
    EnQueue(&Q, 3);
    EnQueue(&Q, 4);
    EnQueue(&Q, 5);
    DeQueue(&Q);
    DeQueue(&Q);
    DeQueue(&Q);
    DeQueue(&Q);
}

 

转载于:https://www.cnblogs.com/EmperLin/p/6550572.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值