队列

队列:动态集合。先进先出。两种操作的执行时间都为O(1)。

伪代码如下:但是我们需要考虑对上溢下溢的检查。

#include<iostream>
using namespace std;
//定义队列
const int n = 100;
struct queue {
	int head;
	int tail;
	int array[n];
};
typedef struct queue* Queue;

void init(Queue q) {
	q->head = 1;
	q->tail = 1;
}
bool empty(Queue q) {
	if (q->head == q->tail) {
		return true;
	}
	return false;
}
//enqueue
void enqueue(Queue q,int x) {
	if (q->head == (q->tail + 1) % n) {
		cerr << "队列为满,不能继续enqueue" << endl;
		return ;
	}
	q->array[q->tail] = x;
	if (q->tail == n) {
		q->tail = 1;
	}
	else {
		q->tail++;
	}
}

//dequeue
int dequeue(Queue q) {
	if (empty(q)) {
		cerr << "队列为空,不能继续dequeue" << endl;
		return 0;
	}
	int x = q->array[q->head];
	if (q->head == n) {
		q->head = 1;
	}
	else {
		q->head++;
	}
	return x;
}
//测试3队列
int main(int argc,char *argv[]){
	int x = 77;
	Queue q = (struct queue*)malloc(sizeof(struct queue));
	init(q);
	enqueue(q, x);
	dequeue(q);
	dequeue(q);
	enqueue(q, x);
	dequeue(q);
	cout << empty(q) << endl;
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HelloHypatia

希望自己的总结对大家有所帮助!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值