【顺序表】循环队列入队与出队

前言

本文章介绍的是循环队列的入队与出队的操作。

题目案例

输入描述

整数n表示n个元素入队

n个元素,用回车隔开

输出描述

输出三个元素

问题分析

  1. 首先应该初始化顺序表。
  2. 循环队列入队是通过改变队尾指针来达到入队的。
  3. 循环队列出队是通过改变队头指针来达到出队的。

 具体代码

#include<iostream>
#include<fstream>
using namespace std;

#define MAXQSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef char QElemType;
typedef char SElemType;
typedef int Status;

typedef struct {
QElemType *base;//初始化时动态分配存储空间
int front;//头指针
int rear;//尾指针
} SqQueue;
Status EnQueue(SqQueue &Q, QElemType e);
Status DeQueue(SqQueue &Q, QElemType &e);
//算法3.11 循环队列的初始化
Status InitQueue(SqQueue &Q) {//构造一个空队列Q
Q.base = new QElemType[MAXQSIZE]; //为队列分配一个最大容量为MAXSIZE的数组空间
if (!Q.base)
exit(OVERFLOW); //存储分配失败
Q.front = Q.rear = 0; //头指针和尾指针置为零,队列为空
return OK;
}

int main() {
SqQueue Q;
QElemType e, j;
int n,i;
InitQueue(Q);
cin>>n; //输入n的值
for(i=0;i<n;i++)
    {
    cin>>e;  //输入e的值
    EnQueue(Q, e);
    }  
while (DeQueue(Q, e)){
cout << e <<endl;    //输出e的值
}
return 0;
}

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){
    if(Q.front == Q.rear) //若队列为空
    {
        return ERROR;
    }
    e = Q.base[Q.front];
    Q.front = (Q.front + 1) % MAXQSIZE;
    return OK;
}

 问题结果

 样例输入

3
A
B
C

样例输出

A
B
C

 ? END


版权声明:本文为weixin_54667422原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。