利用C++实现队列的表示和操作,插入、删除、遍历等(顺序表示)

一、创建sqqueue.h头文件,定义队列并声明函数

#pragma once
#include<iostream>
using namespace std;
#define MAXSIZE 100 //最大队列长度

//队列
struct SqQueue
{
	int* base; //初始化的动态分配存储空间
	int front; //头指针
	int rear; //尾指针
};

//初始化
bool InitQueue(SqQueue& Q);

//插入(入队)
bool InsertQueue(SqQueue& Q, int e);

//删除(出队)
bool DeQueue(SqQueue& Q, int& e);

//遍历
void PrintQueue(SqQueue Q);

//判断是否为空
bool QueueEmpty(SqQueue Q);

//队列长度
int QueueLength(SqQueue Q);

//清空
bool ClearQueue(SqQueue& Q);

//销毁
bool DestroyQueue(SqQueue& Q);

二、创建sqqueue.cpp源文件,将声明的函数做具体实现

#include"sqqueue.h"

//初始化
bool InitQueue(SqQueue& Q)
{
	Q.base = new int[MAXSIZE]; //分配数组空间
	if (!Q.base)
	{
		exit(0);
	}
	Q.front = Q.rear = 0; //头指针尾指针置为0,队列为空
	return true;
}

//插入(入队)
bool InsertQueue(SqQueue& Q, int e)
{
	if ((Q.rear + 1) % MAXSIZE == Q.front) //队满
	{
		return false;
	}
	Q.base[Q.rear] = e; //新元素插入队尾
	Q.rear = (Q.rear + 1) % MAXSIZE; //队尾指针加1
	return true;
}

//删除(出队)
bool DeQueue(SqQueue& Q, int& e)
{
	if (Q.front == Q.rear) //队空
	{
		return false;
	}

	e = Q.base[Q.front]; //保存队头元素
	Q.front = (Q.front + 1) % MAXSIZE; //队头指针加1
	return true;
}

//遍历
void PrintQueue(SqQueue Q)
{
	while (Q.front != Q.rear)
	{
		cout << Q.base[Q.front] << endl; //输出头指针元素
		Q.front = (Q.front + 1) % MAXSIZE; //头指针加1
	}
}

//判断是否为空
bool QueueEmpty(SqQueue Q)
{
	if (Q.front == Q.rear)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//队列长度
int QueueLength(SqQueue Q)
{
	return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}

//清空
bool ClearQueue(SqQueue& Q)
{
	if (Q.base)
	{
		Q.front = Q.rear;
	}
	return true;
}

//销毁
bool DestroyQueue(SqQueue& Q)
{
	if (Q.base)
	{
		delete Q.base;
		Q.front = Q.rear = 0;
	}
	return true;
}

三、在主函数中测试

#include<iostream>
using namespace std;
#include"sqqueue.h"

int main()
{
	//1.创建队列Q,并初始化
	SqQueue Q;
	InitQueue(Q);

	//2.插入数据
	int arr[5] = { 1,2,3,4,5 };
	for (int i = 0; i < 5; i++)
	{
		InsertQueue(Q, arr[i]);
	}
	cout << "插入后元素:" << endl;
	//3.遍历
	PrintQueue(Q);

	//4.删除
	int e;
	DeQueue(Q, e);
	cout << "元素" << e << "以删除" << endl;
	cout << "删除后元素:" << endl;
	PrintQueue(Q);

	//5.判断是否为空
	if (QueueEmpty(Q))
	{
		cout << "队列为空" << endl;
	}
	else
	{
		//6.队列长度
		cout << "队列不为空队列长度为:" << QueueLength(Q) << endl;
	}

	//7.清空
	ClearQueue(Q);
	cout << "清空后遍历:" << endl;
	PrintQueue(Q);

	//8.销毁
	DestroyQueue(Q);
	cout << "销毁后遍历:" << endl;
	PrintQueue(Q);

	system("pause");
	return 0;
}

四、最终结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值