数据结构实验四 基于队列的排序操作

数据结构实验四 基于队列的排序操作

实验任务

仅使用队列的enqueue和dequeue函数将一个循环队列中的元素位置重新调整。
初始时,该循环队列中从队头到队尾的值分别为[1,3,6,4,2,9,7,8],使用enqueue和dequeue函数调整后,从队头到队尾的值分别为[1,2,3,4,6,7,8,9]。请编写代码解决上述问题。
注意:不允许对queue直接排序,因为这将破坏queue结构。

#include <iostream>
#include <algorithm>  //sort函数
using namespace std;
#define ERROR 0
#define OK 1
#define OVERFLOW -2
#define MAXSIZE 100
typedef int QElemType;

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

int InitQueue(SqQueue& Q);  //初始化队列
int EnQueue(SqQueue& Q, QElemType e);  //插入e为Q的新队尾元素
int DeQueue(SqQueue& Q);  //删除Q的队头元素
void PrintQueue(SqQueue& Q);  //输出队列中所有元素

int main()
{
	SqQueue q;
	InitQueue(q);
	for (int i = 0; i < 8; i++)  //元素入队
	{
		int e;
		cin >> e;
		EnQueue(q, e);
	}
	cout << "初始时";
	PrintQueue(q);

	int arr[MAXSIZE], index = 0;
	for (int i = 0; i < (q.rear - q.front + MAXSIZE) % MAXSIZE; i++)
		arr[index++] = q.base[(q.front + i) % MAXSIZE];
	sort(arr, arr + 8);  //对arr排序

	for (int i = 0; i < 8; i++)  //依次将arr中的元素插入队尾,并同时删除队头元素
	{
		EnQueue(q, arr[i]);
		DeQueue(q);
	}
	cout << "调整后";
	PrintQueue(q);

	return 0;
}

int InitQueue(SqQueue& Q)
{
	Q.base = new QElemType[MAXSIZE];
	if (!Q.base) exit(OVERFLOW);
	Q.front = Q.rear = 0;
	return OK;
}
int EnQueue(SqQueue& Q, QElemType e)
{
	if ((Q.rear + 1) % MAXSIZE == Q.front)
		return ERROR;
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MAXSIZE;
	return OK;
}
int DeQueue(SqQueue& Q)
{
	if (Q.front == Q.rear)
		return ERROR;
	Q.front = (Q.front + 1) % MAXSIZE;
	return OK;
}
void PrintQueue(SqQueue& Q)
{
	cout << "队列中的元素为:";
	for (int i = 0; i < (Q.rear - Q.front + MAXSIZE) % MAXSIZE; i++)
		cout << Q.base[(Q.front + i) % MAXSIZE] << ' ';
	cout << endl;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Re:从零开始的代码生活

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值