@【数据结构】(环形队列 基本操作函数)
环形队列基本操作函数:进队,出队,输出队中元素
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#define MAXN 11 /* 定义环行顺序队列的存储长度 */
using namespace std;
typedef int Elemtype;
typedef struct
{
Elemtype data[MAXN];
int front, rear;
}Cseque;
void Init(Cseque &q)
{
q.front = q.rear = 0;
}
int EnQueue(Cseque &q,Elemtype x)/* 进队操作, 返回1:队满 */
{
if((q.rear+1)%MAXN==q.front)
{
cout << "队满" << endl; return 0;
}
else
{
q.rear = (q.rear + 1) % MAXN;
q.data[q.rear] = x;
return 1;
}
}
int DeQueue(Cseque &q, Elemtype *x)/* 出队操作 返回1:队空 */
{
if(q.front==q.rear)
{
cout << "队空" << endl; return 0;
}
else
{
q.front = (q.front + 1) % MAXN;
*x = q.data[q.front ];
return 1;
}
}
void OutputQueue(Cseque &q) /* 输出队列中元素 */
{
if (q.front==q.rear) cout << "队空" << endl;
int i = q.front + 1;
while (i<=q.rear)
{
cout << q.data[i] << " ";
i++;
}
cout << endl;
}
void main()
{
Cseque *q;
q = (Cseque*)malloc(sizeof(Cseque));
Init(*q);
EnQueue(*q, 8); EnQueue(*q, 0); EnQueue(*q, 3); EnQueue(*q, 7); EnQueue(*q, 1);
cout << "初始时循环队中元素为: " << endl;
OutputQueue(*q);
int index, x;
while (1) //永真循环
{
cout << "---------------------------------------------" << endl;
cout << "请选择操作:1:进队 " << endl;
cout << " 2:出队 " << endl;
cout << " 3:输出队列中的元素" << endl;
cout << " 0:退出 " << endl;
cout << "---------------------------------------------" << endl;
cin >> index;
switch (index)
{
case 1:
{
cout << "请输入x:";
cin >> x; EnQueue(*q, x);
cout << x << "进队后:"; OutputQueue(*q);
break;
}
case 2:
{
DeQueue(*q, &x);
cout << x << "出队后:"; OutputQueue(*q);
break;
}
case 3:
{
cout << "输出队中元素:" << endl;
OutputQueue(*q);
break;
}
case 0: break;
}
}
system("pause");
}
测试示例:
进队:
出队:
输出队中元素: