C++数据结构之队列

#include<iostream>

#include <iomanip>
using namespace std;

#define MAXSIZE 5       //设置队列最大容量
typedef int DataType;   //队列中元素的类型

typedef struct Queue
{
	DataType queue[MAXSIZE];
	int front;   //队头指针
	int rear;    //队尾指针
}SeqQueue;

//初始化队列 ,将队列初始化为空队列

void InitQueue(SeqQueue* SQ)
{
	if (!SQ) return;
	//把对头和队尾的指针都置0
	SQ->front = SQ->rear = 0;
}

//判断队列为空
int IsEmpty(SeqQueue* SQ)
{
	if (!SQ) return 0;
	if (SQ->front == SQ->rear)
	{
		return 1;
	}
	return 0;
}
//判断队列是否为满
int IsFull(SeqQueue* SQ)
{
	if (!SQ) return 0;

	if (SQ->rear == MAXSIZE)
	{
		return 1;
	}
	return 0;
}
//入队,将元素data插入到队列 SQ中

int EnterQueue(SeqQueue* SQ, DataType data) {
	if (!SQ) return 0;

	if (IsFull(SQ)) {
		cout << "无法插入元素" << data << endl;
		return 0;
	}
	SQ->queue[SQ->rear] = data; //在队尾插入元素
	SQ->rear++; //队尾指针后移以为
	return 1;
}
//打印队列中的各元素
void PrintQueue(SeqQueue* SQ)
{
	if (!SQ) return;

	int i = SQ->front;
	while (i < SQ->rear)
	{
		cout << setw(4) << SQ->queue[i];
		i++;
	}
	cout << endl;
}
//方式1:出队,将队列中对头的元素data出队 ,后面的元素向前移动

int DeleteQueue(SeqQueue* SQ, DataType* data)
{
	if (!SQ || IsEmpty(SQ)) {
		cout << "队列为空!" << endl;
		return 0;
	}

	if (!data) return 0;
	*data = SQ->queue[SQ->front];

	for (int i = SQ->front + 1; i < SQ->rear; i++) {
		//移动后面的元素
		SQ->queue[i - 1] = SQ->queue[i];
	}
	SQ->rear--;//队尾指针前移一位
	return 1;
}

//出队,将队列中队头的元素 data 出队,出队后队头指针 front 后移一位
int DeleteQueue2(SeqQueue* SQ,DataType* data) { 
	if (!SQ || IsEmpty(SQ)) {
		cout<<"队列为空!"<<endl;
		return 0; 
	}
	if(SQ->front>=MAXSIZE){ 
		cout<<"队列已到尽头!"<<endl;
		return 0;
	}
	*data = SQ->queue[SQ->front]; //出队元素值 
	SQ->front = (SQ->front)+1; //队首指针后移一位 
   return 1;
}
//取队首元素
int GetHead(SeqQueue* SQ, DataType *data) {
	if (!SQ || IsEmpty(SQ))
	{
		cout << "队列为空!" << endl;
	}
	return *data = SQ->queue[SQ->front];
}
//清空队列 
void ClearQueue(SeqQueue* SQ) { 
	SQ->front = SQ->rear = 0;
}
//获取队列中元素的个数
int getLength(SeqQueue* SQ){ 
	if(!SQ) return 0;
	return SQ->rear-SQ->front;
}
int main() {
	SeqQueue* SQ = new SeqQueue; 
	DataType data = -1; 
	//初始化队列
	InitQueue(SQ); 
	//入队
	for(int i=0; i<7; i++){
		EnterQueue(SQ, i);
	}//打印队列中的元素
	printf("队列中的元素(总共%d 个):", getLength(SQ)); 
	PrintQueue(SQ); 
	cout << endl; 
	//出队 //for(int i=0; i<10; i++){
	if(DeleteQueue2(SQ, &data)){
		cout<<"出队的元素是:"<<data<<endl; 
	}else { cout<<"出队失败!"<<endl; } 
	//} 
	//打印队列中的元素 
	printf("出队一个元素后,队列中剩下的元素:");
	PrintQueue(SQ); 
	cout<<endl;
	system("pause");
	return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值