随笔 - 39  文章 - 0  评论 - 0  阅读 - 2716 
复制代码
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <math.h>

/** 循环队列的顺序存储实现
 队列头在队列第一个元素前 不指向元素
 队列尾是指向队列最后一个元素
 */
#define ERROR -1
#define ElementType int

typedef int Position;
struct QNode{
    ElementType *Data;
    Position Front, Rear; // 队列头尾指针
    int MaxSize; // 队列最大容量
};
typedef struct QNode *Queue;

Queue CreateQueue(int MaxSize){
    Queue Q = (Queue)malloc(sizeof(struct QNode));
    Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
    Q->Front = 0;
    Q->Rear = 0;
    Q->MaxSize = MaxSize;
    return Q;
}

// 数组预留一个空位代表队列满
bool IsFull(Queue Q){
    return ((Q->Rear+1)%Q->MaxSize == Q->Front);
}

bool AddQ(Queue Q,ElementType X){
    if(IsFull(Q)){
        printf("Queue is Full\n");
        return false;
    }else{
        Q->Rear = (Q->Rear+1)%Q->MaxSize;
        Q->Data[Q->Rear] = X;
        return true;
    }
}

bool IsEmpty(Queue Q){
    return (Q->Front == Q->Rear);
}

ElementType DeleteQ(Queue Q){ // 出队 并返回出队的元素
    if(IsEmpty(Q)){
        printf("Queue is Empty\n");
        return ERROR;
    }else{
        Q->Front = (Q->Front+1)%Q->MaxSize;
        return Q->Data[Q->Front];
    }
}
int main(){
    Queue q = CreateQueue(10);
    AddQ(q, 0);
    AddQ(q, 1);
    int a;
    a = DeleteQ(q);
    printf("a = %d\n",a);
    AddQ(q, 2);
    a = DeleteQ(q);
    printf("a = %d\n",a);
    a = DeleteQ(q);
    printf("a = %d\n",a);
    a = DeleteQ(q);
    printf("a = %d\n",a);
    return 0;
}
复制代码

 

posted on   Rabbit_XIN  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示