1. 程式人生 > >C語言--迴圈佇列實現

C語言--迴圈佇列實現


#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
/*
	迴圈佇列
*/

typedef struct Queue
{
	int *p_base;
	int front;
	int rear;
} QUEUE,*PQUEUE;

void init_queue(QUEUE *);//佇列初始化

bool en_queue(QUEUE *, int); //加入佇列

void traverse_queue(QUEUE *);

bool is_full(QUEUE *);

bool is_empty(QUEUE *);

bool out_queue(QUEUE *, int
*); int main() { QUEUE queue; int value; init_queue(&queue); en_queue(&queue, 1); en_queue(&queue, 1); en_queue(&queue, 1); en_queue(&queue, 1); en_queue(&queue, 1); traverse_queue(&queue); printf("\n"); out_queue(&queue, &value); printf("%d\n", value); traverse_queue(&queue); return
0; } void init_queue(QUEUE *p_queue) { p_queue->p_base = (int *)malloc(sizeof(int) * 6); p_queue->front = 0; p_queue->rear = 0; return; } bool en_queue(QUEUE * p_queue, int value) { if (is_full(p_queue)) { return false; } else { p_queue->p_base[p_queue->rear] = value; p_queue->rear = (p_queue->rear + 1) % 6; return
true; } } bool is_full(QUEUE *p_queue) { if ((p_queue->rear + 1) % 6 == p_queue->front) { return true; } else { return false; } } void traverse_queue(QUEUE *p_queue) { int i = p_queue->front; while (i != p_queue->rear) { printf("%d ", p_queue->p_base[i]); i = (i + 1) % 6; } return; } bool is_empty(QUEUE *p_queue) { if (p_queue->front == p_queue->rear) { return true; } else { return false; } } bool out_queue(QUEUE *p_queue, int *p_value) { if (is_empty(p_queue)) { return false; } else { *p_value = p_queue->p_base[p_queue->front]; p_queue->front = (p_queue->front + 1) % 6; return false; } }