zoukankan      html  css  js  c++  java
  • 循环队列

    circleQeueu.h 头文件

    #define MAXQSIZE 3
    #define OK 1
    #define ERROR 0
    typedef struct {

    int *base;
    int front;
    int rear;

    }Queue;

    typedef int Status;


    //初始化一个队列
    Status InitQueue(Queue *Q);

    //获取队列中元素的个数
    int QueueLength(Queue Q);

    //向队列队尾插入元素
    Status EnQueue(Queue *Q, int e);

    //删除队头元素
    Status DeQueue(Queue *Q,int *e);

    //查看队列中的所有元素
    Status QueueTraverse(Queue Q);

    ---------------------------------------------------------------------------------

    circleQeueu.c

    #include "stdio.h"
    #include "stdlib.h"
    #include "circleQueue.h"

    void main() {

    Queue Q;

    int length,e;

    //初始化队列
    InitQueue(&Q);

    EnQueue(&Q,1);
    EnQueue(&Q,2);

    //EnQueue(&Q,4);

    length = QueueLength(Q);

    //printf("%d ",length);

    QueueTraverse(Q);
    printf("删除对头元素 ");
    DeQueue(&Q,&e);

    QueueTraverse(Q);
    printf("插入元素 ");
    EnQueue(&Q, 3);
    QueueTraverse(Q);
    printf("删除对头元素 ");
    DeQueue(&Q, &e);
    printf("插入元素 ");
    EnQueue(&Q, 4);
    QueueTraverse(Q);

    }


    //初始化队列
    Status InitQueue(Queue *Q) {

    Q->base = (int *)malloc(MAXQSIZE*sizeof(int));//开辟一定长度的空间
    if (Q->base == NULL) exit(2);
    Q->front = Q->rear = 0;//下标从0开始

    return OK;
    }

    //获取队列中元素的个数
    int QueueLength(Queue Q) {

    return (Q.rear - Q.front + MAXQSIZE)%MAXQSIZE;

    }

    //向队列队尾插入元素
    Status EnQueue(Queue *Q, int e) {

    //判断队列是否已满
    //队尾指针始终指向队列尾元素的下一个元素(并没有物理意义上的满)
    if ((Q->rear + 1) % MAXQSIZE == Q->front) {
    printf("队列已满 ");
    return ERROR;
    }

    Q->base[Q->rear] = e;

    Q->rear = (Q->rear + 1) % MAXQSIZE;

    return OK;

    }

    //删除队头元素
    Status DeQueue(Queue *Q, int *e) {

    //队列为空
    if (Q->front == Q->rear) return ERROR;

    *e = Q->base[Q->front];

    Q->front = (Q->front + 1) % MAXQSIZE;

    return OK;

    }


    Status QueueTraverse(Queue Q) {

    if (Q.front == Q.rear) {

    printf("队列为空 ");
    return OK;
    }
    while (Q.base[Q.front]!=NULL&&Q.front!=Q.rear)
    {
    printf("%d ",Q.base[Q.front]);
    Q.front = (Q.front + 1) % MAXQSIZE;

    }


    }

  • 相关阅读:
    kill eclipse
    C语言之表达式运算整体提升
    查找函数对比:findall,search,match
    Linux backtrace()
    git本地协同
    git 撤销push到服务器的代码
    gtest
    C陷阱篇之enum默认长度
    程序员中文开发者手册
    C语言错题分析
  • 原文地址:https://www.cnblogs.com/paulversion/p/7662675.html
Copyright © 2011-2022 走看看