建立顺序队列结构必须为其静态分配或动态申请一片连续的存储空间,并设置两个指针进行管理。一个是队头指针front,它指向队头元素;另一个是队尾指针tail,它指向下一个入队元素的存储位置
我的链式队列里面讲到,队列的概念和实现方式,现在我们来用数组实现:
首先是比较麻烦的方法,但是是比较能理解的方法
#include<stdio.h>
#include<stdlib.h>
const int MAX = 20;
struct queue {
int* queuem; //数组队列
int frontpos; //队头元素下标
int tailpos; //队尾元素下标
};
这里先创建好队列模型
然后就是创建队列的函数
struct queue* createqueue() {
struct queue* pqueue = (struct queue*)malloc(sizeof(struct queue));
//一维数组的动态内存申请
pqueue->queuem = (int*)malloc(sizeof(int) * MAX);
pqueue->frontpos = pqueue->tailpos = -1;
return pqueue;
}
也就是为数组申请动态内存,还有双指针的初始化
接下来就是入队和出队
也就是两个指针的移动
bool empty(struct queue* pqueue) {
return pqueue->frontpos == pqueue->tailpos;//判断队是否为空
}
void push(struct queue* pqueue, int data) {
//用数组一定要判断是否满了的情况
if (pqueue->tailpos == MAX - 1) {
printf("队满无法入队\n");
return;
}
pqueue->tailpos++;
pqueue->queuem[pqueue->tailpos] = data;
}
//出队与获取头元素放到一起
int pop(struct queue* pqueue) {
if (empty(pqueue)) {
printf("队为空,无法出队");
exit(0);
}
pqueue->frontpos++;
return pqueue->queuem[pqueue->frontpos];
}
下面来测试
int main() {
struct queue* myqueue = createqueue();
push(myqueue, 3);
push(myqueue, 2);
push(myqueue, 1);
push(myqueue, 0);
while (!empty(myqueue)){
printf("%d\t", pop(myqueue));
}
return 0;
}
注意了,数组实现的队列空间都是固定的,存的数据多少是一定的,删除元素也是伪删除,它数据还存在,只不过是我们的指针移动了
下面是最实在,最实用的方法,直接静态的数组实现,也就是模拟这个结构,不管什么方法吧,只要是这种结构都是队列
int main() {
int myqueue[MAX] = { 0 };
int front = -1;
int tail = -1;
int i;
myqueue[++tail] = 4;
myqueue[++tail] = 3;
myqueue[++tail] = 3;
for (i = 1; i < 9; i++) {
myqueue[++tail] = i;
}
while (front != tail) {
printf("%d\t", myqueue[++front]);
}
return 0;
}
好了以上就是数组队列了,他可以运用到好多地方呢。
下一个博客,优先队列