使用数组实现双头队列,参考结构: typedef struct Deque{ Type *array; //数组 int ihead; //头索引 int itail; //尾索引 int entry_count; // 现存数据数量 int array_capacity; // 容量大小 }Deque, *Deque_link;
时间: 2023-09-16 16:10:02 浏览: 111
数组实现队列
下面是使用数组实现双头队列的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#define Type int // 定义元素类型
typedef struct Deque{
Type *array; // 数组
int ihead; // 头索引
int itail; // 尾索引
int entry_count; // 现存数据数量
int array_capacity; // 容量大小
}Deque, *Deque_link;
// 初始化双头队列
void init_deque(Deque_link deque, int capacity) {
deque->array = (Type*)malloc(sizeof(Type) * capacity);
deque->ihead = 0;
deque->itail = capacity - 1;
deque->entry_count = 0;
deque->array_capacity = capacity;
}
// 判断队列是否为空
int is_empty(Deque_link deque) {
return deque->entry_count == 0;
}
// 判断队列是否已满
int is_full(Deque_link deque) {
return deque->entry_count == deque->array_capacity;
}
// 获取队列长度
int size(Deque_link deque) {
return deque->entry_count;
}
// 从队头入队
void push_front(Deque_link deque, Type value) {
if (is_full(deque)) {
printf("Deque is full, cannot push_front!\n");
return;
}
deque->array[deque->ihead] = value;
deque->ihead = (deque->ihead + 1) % deque->array_capacity;
deque->entry_count++;
}
// 从队尾入队
void push_back(Deque_link deque, Type value) {
if (is_full(deque)) {
printf("Deque is full, cannot push_back!\n");
return;
}
deque->array[deque->itail] = value;
deque->itail = (deque->itail - 1 + deque->array_capacity) % deque->array_capacity;
deque->entry_count++;
}
// 从队头出队
Type pop_front(Deque_link deque) {
if (is_empty(deque)) {
printf("Deque is empty, cannot pop_front!\n");
return -1;
}
Type value = deque->array[(deque->ihead - 1 + deque->array_capacity) % deque->array_capacity];
deque->ihead = (deque->ihead - 1 + deque->array_capacity) % deque->array_capacity;
deque->entry_count--;
return value;
}
// 从队尾出队
Type pop_back(Deque_link deque) {
if (is_empty(deque)) {
printf("Deque is empty, cannot pop_back!\n");
return -1;
}
Type value = deque->array[(deque->itail + 1) % deque->array_capacity];
deque->itail = (deque->itail + 1) % deque->array_capacity;
deque->entry_count--;
return value;
}
int main() {
Deque deque;
int capacity = 10;
init_deque(&deque, capacity);
// 从队头入队
for (int i = 0; i < 5; i++) {
push_front(&deque, i);
}
// 从队尾入队
for (int i = 5; i < 10; i++) {
push_back(&deque, i);
}
// 从队头出队
while (!is_empty(&deque)) {
printf("%d ", pop_front(&deque));
}
printf("\n");
// 从队尾出队
for (int i = 0; i < 5; i++) {
push_front(&deque, i);
}
while (!is_empty(&deque)) {
printf("%d ", pop_back(&deque));
}
printf("\n");
return 0;
}
```
在上面的代码中,我们使用了一个数组来存储双头队列中的元素。`ihead` 表示队头的位置,`itail` 表示队尾的位置,`entry_count` 表示队列中现存的元素数量,`array_capacity` 表示数组的容量大小。在初始化双头队列时,我们先动态分配一个数组,并将队头和队尾的位置分别初始化为 0 和 `capacity - 1`。当队列满时,我们无法继续插入元素,当队列为空时,我们无法出队元素。
阅读全文