使用队列打印等腰的杨辉三角
头文件
#ifndef _QUEUE_H
#define _QUEUE_H
#include<stdio.h>
#include<stdlib.h>
#define SIZE 30
#define SUCCESS 10000
#define FAILURE 10001
#define TURE 10002
#define FALSE 10003
struct queue
{
int data[SIZE];
int front;
int rear;
};
typedef struct queue QUE;
int Initqueue(QUE *p); // 初始化
int Emptyqueue(QUE p); // 判断队列是否为空
int Enterqueue(QUE *p,int e); // 进入队列
int Getfrontqueue(QUE p); // 得到队头元素
int Lengthqueue(QUE p); // 求队列长度
int Deletequeue(QUE *p); // 删除队列
#endif
子函数文件
#include"queue.h"
int Initqueue(QUE *p)
{
if(NULL == p)
{
return FAILURE;
}
p->rear = p->front = 0;
return SUCCESS;
}
int Emptyqueue(QUE p)
{
return (p.front == p.rear)? TURE:FALSE;
}
int Enterqueue(QUE *p,int e)
{
if(NULL == p)
{
return FAILURE;
}
if((p->rear+1)%SIZE == p->front)
{
return FAILURE;
}
p->data[p->rear] = e;
p->rear = (p->rear + 1) % SIZE;
return SUCCESS;
}
int Getfrontqueue(QUE p)
{
if(p.front == p.rear)
{
return FAILURE;
}
return p.data[p.front];
}
int Lengthqueue(QUE p)
{
return (p.rear - p.front + SIZE) % SIZE;
}
int Deletequeue(QUE *p)
{
if(NULL == p)
{
return FAILURE;
}
if(p->front == p->rear)
{
return FAILURE;
}
int e = p->data[p->front];
p->front = (p->front+ 1 ) % SIZE;
return e;
}
主函数文件
#include "queue.h"
int main()
{
int n; // 打印的行数
int i=1,j,t,e,len;
QUE p,q; // 定义两个队列
printf("Please input: ");
scanf("%d",&n); // 输入行数
printf("\n");
if(Initqueue(&p) != SUCCESS || Initqueue(&q) != SUCCESS)
{
printf("Init Failure!\n");
}
// 先给 p 队列三个元素,杨辉三角首行(输出时选择大于0的元素)
Enterqueue(&p,0); //队列的头元素为0
Enterqueue(&p,1);
Enterqueue(&p,0); //队列的最后一个元素为0
len = Lengthqueue(p); //求对列p的长度 < SIZE-1
while( i <= n && len < SIZE )
{
if( i%2 != 0 && Emptyqueue(q) == TURE)
{
Enterqueue(&q,0);
t = Deletequeue(&p);
for(j=0;j<3*(n-i);j++) //保证打印的杨辉三角是等腰的
printf(" ");
while(Emptyqueue(p) != TURE)
{
e = t;
if( e > 0 )
{
printf("%6d",e);
}
t = Deletequeue(&p); // 删除队列,就是把每一个队列中的元素进行出队
Enterqueue(&q,e+t);
}
printf("\n");
Enterqueue(&q,0);
i++;
len++;
}
else if( i%2 != 1 && Emptyqueue(p) == TURE)
{
Enterqueue(&p,0);
t = Deletequeue(&q);
for(j=0;j<3*(n-i);j++)
printf(" ");
while(Emptyqueue(q) != TURE)
{
e = t;
if( e > 0 )
{
printf("%6d",e);
}
t = Deletequeue(&q);
Enterqueue(&p,e+t);
}
printf("\n");
Enterqueue(&p,0);
i++;
len++;
}
}
return 0;
}