前言
动态数组队列的基本操作
一、头文件
#ifndef DYNAMIC_QUEUE_H
#define DYNAMIC_QUEUE_H
#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
typedef int ElementType;
#define DEFAULT_CAPACITY 10
#define THRESHOLD 1000
typedef struct {
ElementType* data;//动态数组存储队列,指向元素存储空间的指针
int front;//标记队头元素的索引
int rear;//标记队尾元素下一个位置的索引
int size;
int capacity;
}DynamicQueue;
//基本操作
//创建队列
DynamicQueue* create_queque();
//判空
bool is_empty(DynamicQueue* q);
//判满
bool is_full(DynamicQueue* q);
//入队
bool enqueue(DynamicQueue* q, ElementType data);
//出队并返回队头元素
ElementType dequeue(DynamicQueue* q);
//销毁动态队列
void destroy_queue(DynamicQueue* q);
//扩容
static bool resize_queue(DynamicQueue* q);
#endif // !DYNAMIC_QUEUE_H
二、动态队列的基本操作
#include "queue.h"
//创建动态队列
DynamicQueue* create_queque() {
DynamicQueue *q=calloc(1,sizeof(DynamicQueue));
if (q == NULL) {
printf("error:calloc failed in create_queque.\n");
return NULL;
}
q->data = calloc(DEFAULT_CAPACITY, sizeof(ElementType));
if (q->data == NULL) {
printf("error:calloc failed in create_queque.\n");
return NULL;
}
q->capacity = DEFAULT_CAPACITY;
return q;
}
//判空
bool is_empty(DynamicQueue* q) {
if (q->size == 0) {
return true;
}
else {
return false;
}
}
//判满
bool is_full(DynamicQueue* q) {
if (q->size == q->capacity) {
return true;
}
else {
return false;
}
}
//入队
bool enqueue(DynamicQueue* q, ElementType data) {
if (is_full(q)) {
if (resize_queue(q))
{
;
}
else {
printf("error:resize_queue failed in enqueue.\n");
return false;
}
}//判满
q->data[q->rear] = data;
q->rear = (q->rear + 1) % q->capacity;//循环队列
q->size++;
return true;
}
//出队
ElementType dequeue(DynamicQueue* q) {
if (is_empty(q)) {
printf("DynamicQueue is empty.\n");
exit(1);
}//判空
int item = q->data[q->front];
q->front=(q->front+1)%(q->capacity);
q->size--;
return item;
}
//销毁
void destroy_queue(DynamicQueue* q) {
free(q->data);
q->data = NULL;
free(q);
}
//扩容
static bool resize_queue(DynamicQueue* q) {
int old_capacity = q->capacity;
int new_capacity = old_capacity > THRESHOLD ? old_capacity+(old_capacity>>1) : old_capacity <<1;
ElementType* new_data = malloc(new_capacity * sizeof(ElementType));
if (new_data == NULL) {
printf("error:malloc failed in resize_queue.\n");
return NULL;
}
int curr = q->front;
int idx = 0;
while (idx < q->size ) {
new_data[idx] = q->data[curr];
idx++;
curr = (curr + 1) % q->capacity;
}
free(q->data);
q->data = new_data;//结构体中指向动态数组的指针指向新数组
q->front = 0;
q->rear = q->size ;
q->capacity = new_capacity;
q->size = old_capacity;
return true;
}
四、输出样例
总结
动态数组队列 ,入队时,如果超出了默认capacity需要进行扩容。