循环队列及其基本操作

包含循环队列构造、初始化、入队、出队、创建、输出队列。

# include<iostream>
using namespace std;

# define MAXSIZE 99

//循环队列 
struct Queue{
	int *base;
	int front;
	int rear;
};

//循环队列初始化 
void InitQueue(Queue &Q) {
	Q.base = new int[MAXSIZE];
	Q.front = Q.rear = 0;
}
//循环队列入队
int Push(Queue &Q,int e) {
	if ((Q.rear + 1) % MAXSIZE == Q.front)
		return 0;
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MAXSIZE;

}

//循环队列出队
int pop(Queue &Q) {
	int e;
	if (Q.front == Q.rear)
		return 0;
	e = Q.base[Q.front];
	Q.front = (Q.front + 1) % MAXSIZE;
	return e;	//返回队头 
}

//循环队列的创建
void CreateQueue(Queue &Q) {
	int e;
	int n;
	cout <<	"请输入您要输入的队列长度:";
	cin >> n;
	for(int i = 0;i < n;i++){
		cin >> e;
		Push(Q,e);	//实现在队尾入队 
	}
}

//循环队列输出队列 
void Display(Queue &Q) {
	if (Q.front == Q.rear)
	cout << "队列为空" <<endl; 
	else {
		int i;
		for (i = Q.front; i < Q.rear; i++)
			cout << Q.base[i] << ' ';
	}
	cout << endl;
}

int main() {
	int e; 
	Queue Q;
	InitQueue(Q);
	CreateQueue(Q);
	Display(Q);
	e = pop(Q);
	cout << "队头元素为:" << e << endl; 
	cout << "出队后队列为:";
	Display(Q); 
	return 0;
}

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值