【数据结构学习笔记】c语言创建循环队列(数组)

【数据结构学习笔记】c语言创建循环队列(数组)

#ifndef QUEUE_DAT
 
typedef int Item;
typedef struct node *Queue;
 
Queue create(void);
bool is_empty(Queue q);
bool is_full(Queue q);
void push(Queue q, Item x);
Item pop(Queue q);
void showqueue(Queue q);
 
#endif // !QUEUE_DAT

函数体:

#include<stdio.h>
#include<stdlib.h>
#include"queueDAT2.h"
 
#define MAX 10
 
/*定义结构体*/
struct node
{
        Item *value;
        int front, rear;
};
 
 
/*创建队列*/
Queue create(void)
{
        Queue q;
        q = (struct node *)malloc(sizeof(struct node));
 
        q->value = (Item *)malloc(sizeof(Item));
 
        q->front = MAX - 1;
        q->rear = MAX - 1;
        return q;
}
 
 
/*队空*/
bool is_empty(Queue q)
{
        return q->front == q->rear;
}
 
 
/*队满*/
bool is_full(Queue q)
{
        return (q->rear + 1) % MAX == q->front;
}
 
 
/*入队*/
void push(Queue q, Item x)
{
        if (is_full(q))
                printf("队满!");
 
        q->rear = (q->rear + 1) % MAX;
        q->value[q->rear] = x;
}
 
 
/*出队*/
Item pop(Queue q)
{
        Item x;
        if (is_empty(q))
                printf("队空!");
 
        q->front = (q->front + 1) % MAX;
        x = q->value[q->front];
        return x;
}
 
 
/*显示队列元素*/
void showqueue(Queue q)
{
        int n=0,m;
        while (!is_empty(q))
        {
                q->front = (q->front + 1) % MAX;
                m = q->value[q->front];
                printf(" %d ", m);
                n++;
        }
        for (int i = 0; i < n; i++)
        {
                q->front = (q->front - 1) % MAX;
        }
}

测试函数:

#include<stdio.h>
#include<stdlib.h>
#include"queueDAT2.h"
 
 
int main(void)
{
        Queue p;
        p = create();
        push(p, 3);
        push(p, 27);
        push(p, 15);
        showqueue(p);
        pop(p);
        printf("\n");
        showqueue(p);
        getchar();
}

运行结果:

在这里插入图片描述

posted @ 2022-10-16 23:02  出色的你  阅读(98)  评论(0)    收藏  举报