#include<iostream>
using namespace std;
const int MAXQSIZE = 100;
const int OK = 1;
const int ERROR = 0;
const int overflow = -2;
const int TRUE = 1;
const int FALSE = 0;
typedef int Status;
typedef struct
{
int* base; //初始化的动态分配存储空间
int front; //头指针
int rear; //尾指针
}SqQueue;
/***********函数声明**************/
Status InitQueue(SqQueue& Q);
//构造一个空队列Q
Status EnQueue(SqQueue& Q, int e);
//插入元素e为新的队尾元素
Status DeQueue(SqQueue& Q, int& e);
//若队列不空,则删除Q的队头元素,用e返回其值,并返回OK
Status GetHead(SqQueue Q, int& e);
/*****************主函数*******************/
int main()
{
int n, s, e;
cout << "n = ";//n为行数
cin >> n;
SqQueue Q1;
InitQueue(Q1);
EnQueue(Q1, 0);
EnQueue(Q1, 1);
EnQueue(Q1, 1);
cout << n << "行杨辉三角行:" << endl;
int k = 1;//行值初始化
while (k <= n)
{
cout << '0' << ' '; //设置每行前的元素0
EnQueue(Q1, 0);//插入分界符0
do
{
DeQueue(Q1, s);
GetHead(Q1, e);
if (e != 0)
{
cout << e << ' ';
}
EnQueue(Q1, s + e);
} while (e != 0);
k++;
cout << '0'; //设置每行后的元素0
cout << endl;
}
return OK;
}
/*****************函数定义*******************/
Status InitQueue(SqQueue& Q)
{
Q.base = (int*)malloc(MAXQSIZE * sizeof(int));
if (!Q.base)
{
exit(overflow);
}
Q.front = Q.rear = 0;
return OK;
}
//构造一个空队列Q
Status EnQueue(SqQueue& Q, int e)
{
if ((Q.rear + 1) % MAXQSIZE == Q.front)//队列满
{
return ERROR;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
//插入元素e为新的队尾元素
Status DeQueue(SqQueue& Q, int& e)
{
if (Q.front == Q.rear)
{
return ERROR;
}
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}
//若队列不空,则删除Q的队头元素,用e返回其值,并返回OK
Status GetHead(SqQueue Q, int& e)
{
e = Q.base[Q.front];
return OK;
}
队列的应用--杨辉三角形
最新推荐文章于 2024-07-25 17:43:13 发布