杨辉三角

队列实现杨辉三角

问题描述:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
打印前n项的杨辉三角。

#include"stdio.h"


#define MAX 50
typedef struct{
	int element[MAX];
	int front;//头指针指示器;
	int rear;//尾指针指示器; 
}DuiLie;

int Lie(DuiLie *D)
{
	D->front=D->rear=0;
	return 1;
}

//入队
int inDui(DuiLie *D,int x)
{
	if((D->rear+1)%MAX==D->front)//队满 
	return 0;
	D->element[D->rear]=x; 
	D->rear=(D->rear+1)%MAX;
	return 1;
}

//出队
int outDui(DuiLie *D,int *x)
{
	if(D->rear==D->front)
	return 0;
	*x=D->element[D->front];
	D->front=(D->front+1)%MAX;
	return 1; 
 }
//获取队列的头元素,但不出队; 
int Head(DuiLie *D,int *x)
{
	if(D->rear==D->front)
	return 0;
	*x=D->element[D->front];
	return 1; 
}


int main()
{
	DuiLie D;
	Lie(&D);                                                                
	int i,n,N,temp,x,j;                                                   
	printf("请输入N的值(输入多少就打印前多少行):");
	scanf("%d",&N);
	inDui(&D,1);//将第一行元素入队;
	for(n=2;n<=N+1;n++)
	{
		inDui(&D,1);//第n行的的第一个元素入队
		for(i=1;i<=n-2;i++)
		{
			printf(" ");
			outDui(&D,&temp);
			printf("%d",temp);//打印n-1行的元素
			Head(&D,&x);
			temp=temp+x;
			inDui(&D,temp);
		}
	outDui(&D,&x);
	printf(" ");
	printf("%d",x);//打印n-1行的最后一个元素 
	inDui(&D,1); //第n行最后一个元素入队
	printf("\n");
	}

	while(D.rear==D.front)//打印最后一行元素 
	{
		outDui(&D,&x);
		printf("%d",x);
	}
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值