#include<iostream.h>
#include<stdlib.h>
#define OK 1
#define OVERFLOW -2
#define ERROR 0
typedef int Status;
typedef int ElemType;
#define MAXQSIZE 100 //最大队列长度-1,多留一个元素空间
typedef struct
{
ElemType *base; //动态分配存储空间
int front; //头指针,若队列不空,指向队列头元素
int rear; //尾指针,若队列不空,指向队列尾元素的下一个位置
}SqQueue;
Status InitQueue(SqQueue &Q)
{
//构造一个空队列Q
Q.base=new ElemType[MAXQSIZE];
if(!Q.base)
exit(OVERFLOW); //存储分配失效
Q.front=Q.rear=0;
return OK;
}
void CreatQueue(SqQueue &Q,int n)
{
//插入元素e为Q的新的队尾元素
ElemType e;
cout<<"input ElemType e(n)=";
for(int i=0;i<n;i++)
{
cin>>e;
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXQSIZE;
}
}
int QueueEmpty(SqQueue Q)
{
return Q.rear==Q.front;
}
int QueueFull(SqQueue Q)
{
//判队满
return (Q.rear+1)%MAXQSIZE==Q.front;
}
int GetFront(SqQueue Q,ElemType &x)
{
//取队头
if(QueueEmpty(Q))
return ERROR;
x=Q.base[Q.front];
return OK;
}
int QueueLength(SqQueue Q)
{
//求队列长度
return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
Status EnQueue(SqQueue &Q,ElemType e)
{
//插入元素e为Q的新的队尾元素
if(QueueFull(Q))
return ERROR; //队列满
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXQSIZE;
return OK;
}
Status DeQueue(SqQueue &Q,ElemType &e)
{
//若队列不空,则删除Q的队头元素,
//用e返回其值,并返回OK;否则返回ERROR
if(QueueEmpty(Q))
return ERROR;
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXQSIZE;
return OK;
}
void MakeEmpty(SqQueue &Q)
{
//一个空队列Q
Q.front=Q.rear=0;
}
void YANGHUI(SqQueue &Q,int n)
{
ElemType s,t;
MakeEmpty(Q);
EnQueue(Q,1);
EnQueue(Q,1); //预放入第一行的两个系数
s=0;
for(int i=1;i<=n;i++)
{
//逐行处理
EnQueue(Q,0);
for(int j=1;j<=i+2;j++)
{
//处理第i行的i+2个系数
DeQueue(Q,t); //读取系数
EnQueue(Q,s+t); //计算下一行系数,并进队列
s=t;
if(j!=i+2)
cout<<s<<" "; //打印一个系数,第i+2个为0
}
cout<<endl;
}
}
void VisitQueue(SqQueue Q)
{
//插入元素e为Q的新的队尾元素
SqQueue p=Q;
if(QueueEmpty(Q))
{
cout<<"Queue is Empty!\n";
}
else
{
while(p.front!=p.rear)
{
cout<<p.base[p.front]<<" ";
p.front=(p.front+1)%MAXQSIZE;
}
cout<<endl;
}
}
void main()
{
SqQueue Q;
int n;
ElemType e;
InitQueue(Q);
cout<<"input Queue Length n=";
cin>>n;
//CreatQueue(Q,n);
//VisitQueue(Q);
/*cout<<"QueueLength="<<QueueLength(Q)<<endl;
cout<<"input EnQueue e=";
cin>>e;
if(EnQueue(Q,e))
VisitQueue(Q);
else
cout<<"Queue is Full!\n";
if(!DeQueue(Q,e))
cout<<"Queue is Empty!\n";
else
{
cout<<"De Dueue:\n";
VisitQueue(Q);
}
if(!GetFront(Q,e))
cout<<"Queue is Empty!\n";
else
cout<<"GetFront is"<<e<<endl;*/
YANGHUI(Q,n);
}
来源:https://www.cnblogs.com/yanyanwen/archive/2013/04/23/3039036.html