#include <bits/stdc++.h>
using namespace std;
typedef struct Queue//数据类型
{
int *pBase;// 数组
int front;//下标
int rear;
}QUEUE;
//声明
void init( QUEUE * );//有*可以改变形参的值,一般被调函数形参都是*
//形参是val而不是*val,调用时之间赋值给val而不是把那里的值拿来用
bool enQueue(QUEUE*,int val);// 放入数组,bool要返回有没有成功,2个参数,哪个队列 值
//形参的参数val可以传给其他函数
void traverseQueue(QUEUE*);
bool fullQueue(QUEUE *pQ) ;
bool outQueue(QUEUE* ,int *pval);//int *是形参要在几个函数之间传递用*
bool emptyQueue(QUEUE* pQ);
int main()
{
QUEUE Q; //变量名Q,数据类型是struct queue,现在变量里面有3个成员,没有初始化
int val;
init( &Q); //被调函数是*,主函数是&Q
enQueue(&Q,1);
enQueue(&Q,2);
enQueue(&Q,3);
enQueue(&Q,4);
enQueue(&Q,5);
enQueue(&Q,6);
traverseQueue(&Q);
if( outQueue(&Q,&val))//因为是*pval,所以要用&val
{
cout<<"出队成功,值是:"<<val<<endl;
}
else
cout<<"出队失败!!!"<<endl;
traverseQueue(&Q);
return 0;
}
//初始化
void init( QUEUE *pQ )//pQ放Q的地址
{
//*pQ是Q pBase是数组的首地址 pBase是数组首地址
pQ->pBase = (int *)malloc(sizeof(int) *6); //先造出数,pBase指向数组,数组有6个元素,24个字节
pQ->front = 0;
pQ->rear=0;
}
bool fullQueue(QUEUE *pQ)
{
if( (pQ->rear+1 )%6 == pQ->front)
{
// cout<<"队列已满!入队失败"<<endl;
return true;//看函数名是队满
}
else
return false;
}
//入队
bool enQueue(QUEUE*pQ,int val)
{
if( fullQueue(pQ) )
{
cout<<"队列已满!入队失败。值是:"<<val<<endl;
return false;//满,错
}
else
{
pQ->pBase [pQ->rear]=val;//数组pBase的位置pQ队的队尾, 把值代入
pQ->rear=(pQ->rear+1)%6;//pQ是队名
cout<<"入队完成!值是:"<<val<<endl;
return true;
}
}
//遍历
void traverseQueue(QUEUE* pQ)
{
int i = pQ->front;
while (i != pQ->rear)
{
cout<<"遍历结果"<<pQ->pBase[i]<<endl;//pQ队名,pBase数组名。i即front是下标
i=(i+1)%6; //输出后f后移 但是用f错误,因为用d相当于删了
}
return;
}
//判断队是否已满
bool emptyQueue(QUEUE* pQ)
{
if( pQ->front==pQ->rear)
{
return true;
}
else
return false;
}
//出队
bool outQueue(QUEUE* pQ,int *pval)
{
if( emptyQueue( pQ))
{
return false;
}
else
{
//先把值保存起来
*pval =pQ->pBase[pQ->front];//从头出队
pQ->front= (pQ->front+1)%6;//f移动,f=(f+1)%6
return true;
}
}
数据结构 队列 入队 遍历输出 出队判断队是否已满
最新推荐文章于 2023-06-15 01:26:30 发布