C语言线性表循环队列的基本操作

前言

本程序是数据结构上机实验内容,参考《数据结构(C语言版)》(清华大学出版社)中链表部分的伪代码实现。

题目要求

设计一个循环队列的表示和实现的演示程序,其基本操作有初始化队列、判队列空否、入队列、出队列等功能。

伪代码

#define MAXQSIZE 100

typedef struct{
    QElemType * base;
    int front;
    int rear;
}SqQueue;

//-----------------基本操作单算法描述
Status InitQueue(SqQueue &Q){
        Q.base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
        if (!Q.base) exit(OVERFLOW);
        Q.front = Q.rear = 0;
        return OK;
}

int 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;
    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;
}

实例代码及说明

#include <stdio.h>
#include <stdlib.h>

#define MAXQSIZE 100

#define OVERFLOW    -1
#define ERROR       0
#define OK          1

typedef int QElemType;
typedef int Status;

typedef struct{
    QElemType * base;
    int front;
    int rear;
}SqQueue;

//-----------------基本操作单算法描述
Status InitQueue(SqQueue *Q){
        Q->base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
        if (!Q->base) exit(OVERFLOW);
        Q->front = Q->rear = 0;
        return OK;
}

int 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;
    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;
}


int main()
{
    SqQueue q;
    int i,n,v;

    InitQueue(&q);

    printf("请输入入队列的数据个数:");
    scanf("%d",&i);
    n=i;

    while(i--){
        printf("输入数值:");
        scanf("%d",&v);
        EnQueue(&q,v);
    }
    printf("当前队列中的数据个数:%d\n",QueueLength(q));
    while(n--){
        if(DeQueue(&q,&v)){
            printf("出队列:%d\n",v);
        }else{
            printf("出队列失败\n");
        }
    }

    system("pause");
    return 0;
}

运行结果

运行结果

参考资料

C语言实现顺序栈的基本操作
C语言实现链表的插入、删除、查询操作
C语言实现线性表的插入和删除操作

猜你喜欢

转载自blog.csdn.net/lgj123xj/article/details/72303182