顺序队列的基本操作(C++)

(1)初始化顺序栈;

(2)数据元素入栈;

(3)数据元素出栈;

(4)读栈顶元素;

(5)判定栈空/满操作;

(6)销毁顺序栈。

参考书籍《数据结构》C语言版第2版 人民邮电出版社 

ps: 数据结构实验作业,感觉有错,希望大家批评指正(下附运行结果)。

#include<iostream>
using namespace std;
//顺序队列的基本操作
#define OK 1;
#define ERROR 0;
#define MAXQSIZE 100

typedef  int QElemType;
typedef  int Status;


typedef struct
{
	QElemType *base;
	int front;
	int rear;
}SqQueue;


//(1)初始化顺序队列;
Status InitQueue(SqQueue&Q)
{//构造一个空队列
	Q.base = new QElemType[MAXQSIZE];//分配空间
	if (!Q.base) exit(OVERFLOW);//判读储存失败与否
	Q.front = Q.rear = 0;//头尾指针置为空,即初始化队列为空
	return OK;
}


//(2)数据元素入队;
Status EnQueue(SqQueue &Q, QElemType e)
{
	if ((Q.rear + 1) % MAXQSIZE == Q.front)//判断队满与否
		return ERROR;
	//QEmpty_Full(Q);

	Q.base[Q.rear] = e;//新元素插入队尾
	Q.rear = (Q.rear+1) % MAXQSIZE;//队尾指针+1
	return OK;
}


//(3)数据元素出队;
Status DeQueue(SqQueue &Q, QElemType &e)
{
	if (Q.front == Q.rear) return ERROR;
	//QEmpty_Full(Q);

	e = Q.base[Q.front];
	Q.front = (Q.front+1) % MAXQSIZE;//队头指针+1

	return e;
}


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


//(5)读队头元素;
QElemType GetHead(SqQueue Q)
{
	if (Q.front != Q.rear)
		return Q.base[Q.front];
}


//(6)判定队列空 / 满;
Status QEmpty_Full(SqQueue Q)
{
	if (Q.front == Q.rear)
	{
		cout << "队列为空" << endl;
	}
	else if ((Q.rear + 1) % MAXQSIZE == Q.front)
	{
		cout << "队列为满" << endl;
	}
	else
	{
		return OK;
	}
		
}


//(7)销毁顺序队列;
Status DestroyQueue(SqQueue &Q)
{
	delete(Q.base);

	Q.base = NULL;
	Q.front = Q.rear = 0;
	cout << "队列销毁成功" << endl;
	return OK;

}

//(8)遍历顺序队列。
Status QueueTraverse(SqQueue Q)
{
	if (Q.front == Q.rear)
	{
		cout << "队列为空" << endl;
		return 0;
	}

	while (Q.front != Q.rear)
	{
		cout << Q.base[Q.front] << " ";
		Q.front++;
	}
	cout << endl;
	return OK;
}

void main()
{
	SqQueue Q;
	
	int i=0;

	InitQueue(Q);

	cout << "请输入入队个数:";
	cin >> i;

	cout <<"请输入入队元素 "<< endl;
	for (int j = 0; j < i; j++)//循环入队
	{
		QElemType e;
		cin >> e;
		EnQueue(Q, e);
	}


	cout << "遍历队列:";
	QueueTraverse(Q);
	

	QEmpty_Full(Q);
	cout << endl;


	cout << "队列头元素为:" << GetHead(Q) << endl;


	cout << "出队元素:";
	for (int j = 0; j < i; j++)//循环入队
	{
		QElemType e;
		cout << DeQueue(Q, e) << " ";
	}
	cout << endl;

	QEmpty_Full(Q);

	cout << endl; 
	DestroyQueue(Q);



	system("pause");
}

  • 7
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值