数据结构实验四 基于队列的排序操作
实验任务
仅使用队列的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;
}