循环队列数组实现
2010-10-23 13:17
567 查看
循环队列的数组实现:
queue.c
queue.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "queue.h" #define SAFE_FREE(q) {if (q) {free(q); q = NULL;}} struct QueueRecord { int capacity; int front; int rear; int size; ElementType *array; }; int IsEmpty(Queue q) { return q->size == 0; } int IsFull(Queue q) { return q->size == q->capacity; } Queue CreateQueue(int maxElements) { Queue q = malloc(sizeof(struct QueueRecord)); if (q == NULL) { fprintf(stderr, "create queue failed."); return NULL; } q->array = malloc(maxElements * sizeof(char)); if (q->array == NULL) { fprintf(stderr, "create queue failed."); return NULL; } q->capacity = maxElements; q->front = q->rear = 0; q->size = 0; return q; } void DisposeQueue(Queue q) { if (q == NULL) { fprintf(stderr, "the queue is NULL."); return; } SAFE_FREE(q->array); SAFE_FREE(q); } void MakeEmpty(Queue q) { if (q == NULL) { fprintf(stderr, "the queue is NULL."); return; } q->front = q->rear = 0; q->size = 0; memset(q->array, 0x00, q->capacity); } int Enqueue(ElementType x, Queue q) { if (IsFull(q)) { fprintf(stderr, "queue is full."); return -1; } if (IsEmpty(q)) { q->array[q->front] = x; } else { if ((q->rear + 1) == q->capacity) { q->rear = 0; q->array[q->rear] = x; } else { q->array[++q->rear] = x; } } q->size++; printf("size = %d\n", q->size); return 0; } int Dequeue(Queue q) { if (IsEmpty(q)) { fprintf(stderr, "queue is empty."); return -1; } q->array[q->front] = 0; if ((q->front + 1) == q->capacity) { q->front = 0; } else { q->front++; } q->size--; return 0; } ElementType Front(Queue q) { if (q == NULL) { fprintf(stderr, "queue is empty."); return -1; } return q->array[q->front]; }
相关文章推荐
- 数据结构(java语言描述)-- 队列的循环数组实现
- 数据结构之循环数组实现队列
- 循环队列_数组实现
- c语言数组方式实现静态循环队列
- 队列的C语言实现(循环数组结构)
- 队列实现对有n个元素的数组循环左移k位
- java队列的循环数组实现
- 队列(queue)的链表(list)实现及循环数组(circular array)实现 C++实现
- 循环数组实现一个队列
- java使用数组实现循环队列
- 循环队列—数组实现
- 循环队列拾遗-使用数组实现循环队列
- Java数组实现循环队列、Java链表实现队列
- 循环队列的数组表示函数的实现
- 基于数组的循环队列(C++模板实现)
- 基于数组的循环队列(C++模板实现)
- C++用数组实现栈和循环队列
- c语言用简单数组实现循环队列
- 《大话数据结构》读书笔记之 队列抽象数据类型(数组实现循环队列)
- 8.用定长数组 实现 循环队列