1. 程式人生 > >基於 Linux 的迴圈佇列實現程式碼

基於 Linux 的迴圈佇列實現程式碼

/*************************************************************************
  > File Name: cyclequeue.c
  > Author: Wenfei6316
  > Mail: [email protected] 
  > Created Time: 2018年06月18日 星期一 23時04分44秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAXSIZE 25

typedef enum{false, true} bool;
typedef int data_t;
typedef struct
{
	data_t data[MAXSIZE];
	int front;
	int rear;
}SqQueue;

SqQueue *CreateEmptyQueue(void);
void EnQueue(SqQueue *queue, data_t value);
bool FullQueue(SqQueue *queue);
void DeQueue(SqQueue *queue, data_t *value);
bool EmptyQueue(SqQueue *queue);
bool DestroyQueue(SqQueue *queue);

int main(int argc, const char *argv[])
{
	data_t data;
	SqQueue *squeue;
	squeue = CreateEmptyQueue();

	EnQueue(squeue, 20);
	EnQueue(squeue, 30);
	EnQueue(squeue, 40);

	DeQueue(squeue, &data);
	printf("DeQueue: %d\n", data);
	DeQueue(squeue, &data);
	printf("DeQueue: %d\n", data);
	DeQueue(squeue, &data);
	printf("DeQueue: %d\n", data);
	DeQueue(squeue, &data);
	printf("DeQueue: %d\n", data);

	for (data=0; data<30; data++)
		EnQueue(squeue, data);
	if (DestroyQueue(squeue))
		printf("Destroy queue success!\n");

	return 0;
}

//建立空的迴圈佇列
SqQueue *CreateEmptyQueue(void)
{
	SqQueue *squeue;
	squeue = (SqQueue *)malloc(sizeof(SqQueue));
	if (squeue == NULL)
	{
		perror("Create cycle queue failed!\n");
		exit(EXIT_FAILURE);
	}
	squeue->front = 0;
	squeue->rear = 0;

	return squeue;
}

//檢查是否為滿佇列
bool FullQueue(SqQueue *queue)
{
	if (queue == NULL)
	{
		printf("Empty queue error!\n");
		exit(EXIT_FAILURE);
	}

	if ((queue->rear+1)%MAXSIZE == queue->front)
		return true;
	else
		return false;
}

//插入元素
void EnQueue(SqQueue *queue, data_t value)
{
	if (FullQueue(queue))
	{
		printf("Queue is full!\n");
		return ;
	}
	queue->data[queue->rear] = value;
	queue->rear = (queue->rear + 1) % MAXSIZE;

	return ;
}

//檢驗是否為空佇列
bool EmptyQueue(SqQueue *queue)
{
	if (queue == NULL)
	{
		printf("Empty queue error!\n");
		exit(EXIT_FAILURE);
	}
	if (queue->rear == queue->front)
		return true;
	else
		return false;
}

//刪除元素
void DeQueue(SqQueue *queue, data_t *value)
{
	*value = 0;
	if (EmptyQueue(queue))
	{
		printf("Queue is empty!\n");
		return ;
	}
	*value = queue->data[queue->front];
	queue->front = (queue->front + 1) % MAXSIZE;

	return ;
}

//銷燬佇列
bool DestroyQueue(SqQueue *queue)
{
	if (queue == NULL)
	{
		printf("Destroy queue is NULL!\n");
		return true;
	}
	free(queue);
	queue = NULL;

	return true;
}