/*
循环队列
VS2010 调试
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define MAX_SIZE 6
#define TRUE 1
#define FALSE 0
#define OVERFLOW 0
#define OK 1
#define ERROR 0
typedef struct seq_queue
{
int front;
int rear;
int *data;
}sq;
/*
函数功能: 初始化循环队列
*/
int init_seq_queue(sq *Q)
{
Q->data = (int *)malloc(MAX_SIZE * sizeof(int));
if(!Q->data)
{
return ERROR;
}
Q->front = 0;
Q->rear = 0;
return OK;
}
/*
函数功能: 队列元素是否为空
返 回 值: 1 为空; 0 非空
*/
int is_queue_empty(sq Q)
{
return ((Q.front == Q.rear) ? TRUE : FALSE);
}
/*
函数功能: 队列是否已满
返 回 值: 1 已满; 0 未满
*/
int is_queue_full(sq Q)
{
return (((Q.rear+1) % MAX_SIZE == Q.front) ? TRUE : FALSE);
}
/*
函数功能: 元素num入队
*/
int enqueue(sq *Q, int num)
{
if(is_queue_full(*Q))
{
return OVERFLOW;
}
Q->rear = (Q->rear + 1) % MAX_SIZE;
Q->data[Q->rear] = num;
return OK;
}
/*
函数功能: 元素出队,出队元素存入num
*/
int dequeue(sq *Q, int *num)
{
if(is_queue_empty(*Q))
{
return ERROR;
}
Q->front = (Q->front + 1) % MAX_SIZE;
*num = Q->data[Q->front];
return OK;
}
/*
函数功能: 获取队头元素,元素存入num
*/
int get_elem(sq Q, int *num)
{
if (is_queue_empty(Q))
{
return ERROR;
}
*num = Q.data[Q.front + 1];
return OK;
}
/*
函数功能: 获得队列长度
返 回 值: 队列长度
*/
int get_queue_length(sq Q)
{
return ((Q.rear - Q.front) + MAX_SIZE) % MAX_SIZE;
}
/*
函数功能: 打印队列元素
*/
void print_queue(sq Q)
{
int i = Q.front + 1;
if(is_queue_empty(Q))
{
return ;
}
printf("FRONT<-");
while(i != ((Q.rear + 1) % MAX_SIZE))
{
printf("%d<-", Q.data[i]);
i = (i + 1) % MAX_SIZE;
}
printf("REAR\n");
}
/*
函数功能: 销毁队列
*/
void destory_queue(sq *Q)
{
free(Q->data);
}
int main(int argc, char *argv[])
{
int num = 0;
sq seq_queue;
init_seq_queue(&seq_queue);
enqueue(&seq_queue, 4);
enqueue(&seq_queue, 5);
enqueue(&seq_queue, 6);
enqueue(&seq_queue, 7);
print_queue(seq_queue);
dequeue(&seq_queue, &num);
print_queue(seq_queue);
enqueue(&seq_queue, 8);
print_queue(seq_queue);
destory_queue(&seq_queue);
return 0;
}
循环队列的实现(C语言)
最新推荐文章于 2022-02-08 17:38:30 发布