队列实例程序(C语言)
/* queue.h */ #ifndef _QUEUE_H #define _QUEUE_H struct queue_record; typedef struct queue_record *queue; int is_empty( queue q ); int is_full( queue q ); queue create_queue( int max_elements ); void dispose_queue( queue q ); void make_empty( queue q ); void enqueue( int x, queue q ); int front( queue q ); void dequeue( queue q ); int front_and_dequeue( queue q ); #endif
/* queue.c */ #include "queue.h" #include <stdio.h> #include <stdlib.h> #define MIN_QUEUE_SIZE 5 struct queue_record { int capacity; int front; int rear; int size; int *array; }; void make_empty( queue q ) { q->size = 0; q->front = 1; q->rear = 0; } int is_empty( queue q ) { return q->size == 0; } int is_full( queue q ) { return q->size == q->capacity; } queue create_queue( int max_elements ) { queue q; if( max_elements < MIN_QUEUE_SIZE ) { printf("Queue size is too small!\n"); exit(0); } q = malloc( sizeof(struct queue_record) ); if(q == NULL) { printf("Out of space!\n"); exit(1); } q->array = malloc(sizeof(int) * max_elements); if(q->array == NULL) { printf("Out of space!\n"); exit(1); } q->capacity = max_elements; make_empty(q); return q; } static int succ( int value, queue q ) { if( ++value == q->capacity ) value = 0; return value; } void enqueue( int x, queue q ) { if( is_full( q ) ) { printf("full queue!\n"); exit(0); } else { q->size++; q->rear = succ( q->rear, q ); q->array[q->rear] = x; } } void dequeue( queue q ) { if( is_empty( q ) ) { printf("empty queue!\n"); exit(0); } else { q->size--; q->front = succ( q->front, q ); } } int front( queue q ) { if( is_empty( q ) ) { printf("empty queue!\n"); exit(0); } else return q->array[q->front]; } int front_and_dequeue( queue q ) { int tmp; if( is_empty( q ) ) { printf("empty queue!\n"); exit(0); } else { tmp = q->array[q->front]; q->size--; q->front = succ( q->front, q ); return tmp; } } void dispose_queue( queue q ) { if( q != NULL ) { free(q->array); free(q); } }
/* queue_test.c */ #include "queue.h" #include <stdio.h> int main(void) { queue q; int tmp; int i; q = create_queue(10); printf("1 enqueue\n"); enqueue(1, q); printf("2 enqueue\n"); enqueue(2, q); printf("3 enqueue\n"); enqueue(3, q); printf("4 enqueue\n"); enqueue(4, q); printf("5 enqueue\n"); enqueue(5, q); printf("\n"); for(i=0; i<5; i++) { printf("dequeue %d\n", front_and_dequeue( q )); } }
测试结果: