数据结构之数组队列

建立顺序队列结构必须为其静态分配或动态申请一片连续的存储空间,并设置两个指针进行管理。一个是队头指针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;
}

好了以上就是数组队列了,他可以运用到好多地方呢。
下一个博客,优先队列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值