我们可以将队列想成一个·线型的管道
所以我们要制造一个管道及需要队列初始化函数,管道需要进入东西,这需要入队函数,管道需要排除(释放)东西,这需要出队函数
请看代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cstdlib>
using namespace std;
#define SIZE 20
typedef struct Data
{
char info;
}DATA;
typedef struct queue
{
DATA queues[SIZE];
int rear;//队尾
int front;//队头
}Queue;
Queue *InitQueue( )//初始化队列
{
Queue *p;
if((p=(Queue *)malloc(sizeof(Queue)))==NULL)
{
cout<<"分配内存失败"<<endl;
exit(1);
}
p->rear=0;
p->front=0;
return p;
}
void InQueue(Queue *p,char information )//入队(我们要考虑的是否队列已满)
{
if(p->rear==SIZE)
{
cout<<"队列已满"<<endl;
}
else
{
p->queues[p->rear++].info=information;//希望各位客官能够明白(理解)p->rear++的作用
//改代码先执行p->queues[p->rear]=information 然后执行p->rear加1
}
}
void OutQueue(Queue *p)//出队(我们要考虑的是否队列为空)
{
if(p->rear==p->front)
{
cout<<"队列为空"<<endl;
}
else
{
cout<<p->queues[p->front++].info<<endl;
}
}
int main()
{
Queue *p;
char information;
p=InitQueue();
cout<<"请输入十个字符"<<endl;
for(int i=0;i<10;i++)
{
cin>>information;
InQueue(p,information);
}
cout<<"出队结果"<<endl;
for(int i=0;i<10;i++)
{
OutQueue(p);
}
cout<<"这就是先进先出(后进后出)"<<endl;
return 0;
}
想到队列我们要想到队列先入先出(后入后出)的特点。