#include<iostream>
using namespace std;
#define MAXSIZE 10//定义数组长度
//定义队列结构体,结构体中包含int类型数组的首地址base和队列的头指针和尾指针
struct queue
{
int* base;
int front;
int rear;
};
//初始化队列
void initqueue(queue &q)
{
q.base = new int[MAXSIZE];
if (!q.base)
{
return;
}
q.front = 0;
q.rear = 0;
}
//获取队列的长度
//由于采用循环队列,计算公式如下,可以自行画图查看
int queuelength(queue q)
{
return (q.rear - q.front + MAXSIZE) % MAXSIZE;
}
//从队尾插入数据
void enqueue(queue &q, int e)
{
if ((q.rear + 1) % MAXSIZE == q.front)
{
cout << "队列已满!" << endl;
return;
}
q.base[q.rear] = e;
cout << q.base[q.rear] << endl;
q.rear = (q.rear + 1) % MAXSIZE;
cout << "rear:" << q.rear << endl;
}
//从队头弹出数据
void popque(queue &q, int &e)
{
if (q.front == q.rear)
{
cout << "队列为空!" << endl;
return;
}
e = q.base[q.front];
q.front = (q.front + 1) % MAXSIZE;
}
//获取头节点数据
int gethead(queue q)
{
if (q.front == q.rear)
{
cout << "队列为空!" << endl;
}
else
{
return q.base[q.front];
}
}
int main()
{
queue q;
initqueue(q);
int a = 0, b = 1, c = 2;
enqueue(q, a);
enqueue(q, b);
enqueue(q, c);
for (int i = 0; i < 3; i++)
{
cout << q.base[i] << endl;
}
cout << queuelength(q) << endl;
system("pause");
return 0;
}
12-10
3468
03-31
74
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交