循环队列的实现(C语言)

/*
	循环队列
	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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值