核心思想:第一步:先创建队列1存放0,1,0三个数,再创建一个空队列2,首位置添0,取0,1相加进入 队列2,取1,0相加进入队列2,然后队列2末尾添0,清空队列1
第二步:队列1首尾添0,取队列2前两位相加进入队列1,取队列2第2,3位相加进入队列1.......队列1末尾添0;
如此往复,写出杨辉三角形
#ifndef _YANGHUI_H
#define _YANGHUI_H
#define SUCCESS 10000
#define FAILURE 10001
#define SIZE 100
struct senquencequeue1
{
int data1[SIZE];
int rear1;
int front1;
};
typedef struct senquencequeue1 Queue1;
struct senquencequeue2
{
int data2[SIZE];
int rear2;
int front2;
};
typedef struct senquencequeue2 Queue2;
int Q1init(Queue1 *q1);
int Q2init(Queue2 *q2);
int yanghui(Queue1 *q1, Queue2 *q2);
#endif
#include "yanghui.h"
#include <stdio.h>
int Q1init(Queue1 *q1)
{
if(NULL == q1)
{
return FAILURE;
}
q1->rear1 = q1->front1 = 0;
return SUCCESS;
}
int Q2init(Queue2 *q2)
{
if(NULL == q2)
{
return FAILURE;
}
q2->rear2 = q2->front2 = 0;
return SUCCESS;
}
int Q1enter(Queue1 *q1)
{
if(NULL == q1)
{
return FAILURE;
}
q1->data1[q1->front1] = 0;
q1->rear1 = (q1->rear1 + 1) % SIZE;
q1->data1[q1->rear1] = 1;
q1->rear1 = (q1->rear1 + 1) % SIZE;
q1->data1[q1->rear1] = 0;
q1->rear1 = (q1->rear1 + 1) % SIZE;
return SUCCESS;
}
int yanghui(Queue1 *q1, Queue2 *q2)
{
int n = 0, k = 0, e, i; //n为输入行数 k为执行次数 e用来存放数据
if(NULL == q1 || NULL == q2)
{
return FAILURE;
}
printf("请输入需要显示的行数!\n");
scanf("%d", &n);
while(1)
{
for(i = 0; i < q1->rear1; i++)
{
printf("%d ", q1->data1[i]);
}
printf("\n");
q2->data2[q2->rear2] = 0;
q2->rear2 = (q2->rear2 + 1) % SIZE;//队列2起始添0
while(q1->rear1 != q1->front1)
{
e = q1->data1[q1->front1] + q1->data1[q1->front1 + 1];
q2->data2[q2->rear2] = e;
q2->rear2 = (q2->rear2 + 1) % SIZE;
q1->front1 = (q1->front1 + 1) % SIZE;
}
q1->rear1 = q1->front1 = 0;//清空队列1
k++;
if(k == n)
{
return 0;
}
for(i = 0; i < q2->rear2; i++)
{
printf("%d ", q2->data2[i]);
}
printf("\n");
q1->data1[q1->rear1] = 0;
q1->rear1 = (q1->rear1 + 1) % SIZE;//队列1起始添0
while(q2->rear2 != q2->front2)
{
e = q2->data2[q2->front2] + q2->data2[q2->front2 + 1];
q1->data1[q1->rear1] = e;
q1->rear1 = (q1->rear1 + 1) % SIZE;
q2->front2 = (q2->front2 + 1) % SIZE;
}
q2->rear2 = q2->front2= 0;//清空队列2
k++;
if(k == n)
{
return 0;
}
}
}
#include "yanghui.h"
#include <stdio.h>
int main()
{
Queue1 Q1;
Queue2 Q2;
int i = 0, ret;
ret = Q1init(&Q1);
if(ret == FAILURE)
{
printf("Q1init failure!\n");
}
else
{
printf("Q1init success!\n");
}
ret = Q2init(&Q2);
if(ret == FAILURE)
{
printf("Q2init failure!\n");
}
else
{
printf("Q2init success!\n");
}
ret = Q1enter(&Q1);
if(ret == FAILURE)
{
printf("Q1enter failure!\n");
}
else
{
printf("Q1enter success!\n");
}
ret = yanghui(&Q1,&Q2);
if(ret == FAILURE)
{
printf("failure!\n");
}
}