循环队列(创建队列,入队,出队)C语言实现

# 下面给出的代码是循环队列的基础操作,代码注释写的还算详细,帮助大家理解,同时也有助于我回忆 在这里插入代码片

#include<stdio.h>
#define qsize 5

int qdata[5],i=0;
struct	cell///单个结点
{
    
    
    int data;
};
struct queue///队列
{
    
    
    struct cell *base;
    int front;
    int rear;
};

int Enqueue(struct queue *q,struct cell e)///入队列(用返回值0或1来判断队列是否满)
{
    
    
    if( (q->rear+1) % qsize == q->front )///队列满
    {
    
    
        printf("Queue is full! \n");
        return 0;
    }
    else
    {
    
    
        q->base[q->rear] = e;///新值给队尾
        q->rear = ( q->rear+1 )%qsize;///队尾指针后移
        return 1;
    }
}

int Dequeue(struct queue *q,struct cell *e)///出队列(用返回值0或1来判断队列是否为空)
{
    
    
    if( q->front == q->rear )///队列空
    {
    
    
        printf("Queue is empty! \n");
        return 0;
    }
    else
    {
    
    
        *e = q->base[q->front];///队首元素给e
        q->front = ( q->front+1 )%qsize;///队首后移
        return 1;
    }
}

main()
{
    
    
    int x;
    struct queue *q;
    struct cell	e;
    q = (struct queue *)malloc(sizeof(struct queue)); ///分配队列的内存
    printf("'0'初始化队列;'1'入队列;'2'出队列\n");
    scanf("%d",&x);
    while(x!=-1)
    {
    
    
        int i;
        if((x-0)<1e-6)
        {
    
    
            q->base = (struct cell *)malloc(qsize*sizeof(struct cell)); ///分配结点的内存
            q->front = q->rear = 0;
        }
        else if((x-1)<1e-6)
        {
    
    
            e.data = 1;///入队的元素赋1
            i=Enqueue(q,e);
            if((i-1)<1e-6)///如果队列未满,则输出入队的信息语句
            {
    
    
                printf("Enter: %d\n",e.data);
            }
        }
        else if((x-2)<1e-6)
        {
    
    
            i=Dequeue(q,&e);
            if(i==1)///如果队列未空,则输出出队的信息语句
            {
    
    
                printf("Output: %d\n",e.data);
            }
        }
        else printf("the input data is only -1,0,1,2 ");
        scanf("%d",&x);
    }
}

##欢迎大家指正错误

猜你喜欢

转载自blog.csdn.net/weixin_46250447/article/details/106677556