用队列可以节省一半的空间,队列的空间复杂度就要低了
这是我写的队列杨辉三角,是金字塔状的。供大家参考。
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<process.h>
#define TRUE 1
#define ERROR 0
#define OK 1
#define FALSE 0
#define OVERFLOW -2
#define MAXSIZE 100;
typedef int Status;
typedef int Boolean;
typedef int Qelemtype;
typedef struct{
Qelemtype *base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue &Q)
{
Q.base = (Qelemtype *)malloc(100*sizeof(Qelemtype));
if(!Q.base) exit(ERROR);
Q.front = Q.rear = 0;
return OK;
}
Status EnQueue(SqQueue &Q,Qelemtype e)
{
if( (Q.rear+1)%100 == Q.front )
return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear+1)%MAXSIZE;
return OK;
}
Status DeQueue(SqQueue &Q,Qelemtype &e)
{
if(Q.front == Q.rear)
return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front+1)%MAXSIZE;
return OK;
}
Status GetHead(SqQueue &Q, Qelemtype &x)
{
if(Q.front == Q.rear)
return ERROR;
x = Q.base[Q.front];
return OK;
}
void YHTriangle()
{
SqQueue Q;
Qelemtype e,x;
int i,j,n;
InitQueue(Q);
EnQueue(Q,1);
cout<<"Please enter the value of n:";
cin>>n;
for(i=1;i<=n;++i)
{
EnQueue(Q,1);
cout<<endl;
for(j=1;j<=i-1;++j)
{
DeQueue(Q,e);
cout<<e<<' ';
GetHead(Q,x);
e=e+x;
EnQueue(Q,e);
}
DeQueue(Q,x);
cout<<x<<' ';
EnQueue(Q,1);
}
}
void main()
{
char a;
do{
YHTriangle();
cout<<endl;
cout<<"Do you want to do it again?(y/n)";
cin>>a;
if( a!='y'&&a!='n')
cout<<"\a\a\a"<<"Please enter right and enter again!"<<endl;
}while( (a=='y')&&(a!='n') );
}
这是我写的队列杨辉三角,是金字塔状的。供大家参考。
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<process.h>
#define TRUE 1
#define ERROR 0
#define OK 1
#define FALSE 0
#define OVERFLOW -2
#define MAXSIZE 100;
typedef int Status;
typedef int Boolean;
typedef int Qelemtype;
typedef struct{
Qelemtype *base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue &Q)
{
Q.base = (Qelemtype *)malloc(100*sizeof(Qelemtype));
if(!Q.base) exit(ERROR);
Q.front = Q.rear = 0;
return OK;
}
Status EnQueue(SqQueue &Q,Qelemtype e)
{
if( (Q.rear+1)%100 == Q.front )
return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear+1)%MAXSIZE;
return OK;
}
Status DeQueue(SqQueue &Q,Qelemtype &e)
{
if(Q.front == Q.rear)
return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front+1)%MAXSIZE;
return OK;
}
Status GetHead(SqQueue &Q, Qelemtype &x)
{
if(Q.front == Q.rear)
return ERROR;
x = Q.base[Q.front];
return OK;
}
void YHTriangle()
{
SqQueue Q;
Qelemtype e,x;
int i,j,n;
InitQueue(Q);
EnQueue(Q,1);
cout<<"Please enter the value of n:";
cin>>n;
for(i=1;i<=n;++i)
{
EnQueue(Q,1);
cout<<endl;
for(j=1;j<=i-1;++j)
{
DeQueue(Q,e);
cout<<e<<' ';
GetHead(Q,x);
e=e+x;
EnQueue(Q,e);
}
DeQueue(Q,x);
cout<<x<<' ';
EnQueue(Q,1);
}
}
void main()
{
char a;
do{
YHTriangle();
cout<<endl;
cout<<"Do you want to do it again?(y/n)";
cin>>a;
if( a!='y'&&a!='n')
cout<<"\a\a\a"<<"Please enter right and enter again!"<<endl;
}while( (a=='y')&&(a!='n') );
}