队列的建立及操作

数据结构与算法 --> 实验报告 4

实验项目名称:队列的建立及操作

一、 实验目的

1.掌握队列存储结构的表示和实现方法。

2.掌握队列的入队和出队等基本操作的算法实现。

二、 实验题

建立顺序循环队列,并在顺序循环队列上实现入队、出队基本操作。

三、 实验过程及结果

①基本思路:

采用一种循环的结构去实现队列的顺序存储,队满和队空时标志都是 Q->front=Q->rear;为了区别两种情况,
我的思路是:修改队满条件,浪费一个元素空间,当只有一个空闲单元时队满。

程序代码:

#include<stdio.h>

#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define MAXSIZE 10
typedef int QElemType;
typedef struct
{
QElemType \*base;
int front;
int rear;
}SqQueue;

Status InitQueue(SqQueue \*Q)
{

    Q->base = (QElemType *)malloc(MAXSIZE * sizeof(QElemType));
    if (Q->base==NULL) exit(OVERFLOW);
    Q->front = Q->rear = 0;
    return OK;

}
Status EnQueue(SqQueue \*Q,QElemType e)
{

    if ((Q->rear + 1) % MAXSIZE == Q->front)
        return ERROR;
    Q->base[Q->rear] = e;
    Q->rear = (Q->rear + 1) % MAXSIZE;
    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) % MAXSIZE;
    return OK;

}
int main() {
SqQueue Q;
QElemType e;
InitQueue(&Q);
for (int i = 2; i < 7; i++)
{
EnQueue(&Q, i);
printf("入队元素为%d\n", i);
}
for (int j=2; j <7; j++) {
DeQueue(&Q, &e);
printf("出队元素为%d\n", e);
}
return 0;
}

②实验结果:

四、 实验总结

队列的顺序存储采用循环队列,为了区分队空和队满,当只有一个空闲单元时队满。
队空条件:front =rear.
队满条件:(rear+1)mod MAXSIZE=front .

posted @ 2020-05-27 20:39  Just-Code-it  阅读(298)  评论(0)    收藏  举报