当前位置:主页 > 查看内容

队列练习——杨辉三角

发布时间:2021-08-18 00:00| 位朋友查看

简介:杨辉三角杨辉三角,是二项式系数在三角形中的一种几何排列。 C++代码实现 /*队列————杨辉三角#include iostream #include stdlib.h using namespace std;#define OK 1#define ERROR -1#define OVERFLOW -2typedef int Status;typedef int QElemType;#def……
杨辉三角杨辉三角,是二项式系数在三角形中的一种几何排列。

C++代码实现

/*
队列————杨辉三角
#include iostream 
#include stdlib.h 
using namespace std;
#define OK 1
#define ERROR -1
#define OVERFLOW -2
typedef int Status;
typedef int QElemType;
#define MAXSIZE 100
typedef struct Qnode {
 QElemType data;
 struct Qnode* next;
}Qnode, * QueuePtr;
typedef struct {
 QueuePtr front;
 QueuePtr rear;
}LinkQueue;
Status InitLQueue(LinkQueue Q) {
 Q.front = new Qnode;
 if (!Q.front) exit(OVERFLOW);
 Q.rear = Q.front;
 Q.front- next = NULL;
 return OK;
// 判断链队列是否为空
bool LQueueEmpty(LinkQueue Q) {
 return (Q.front == Q.rear);
// 入队
Status PushLQueue(LinkQueue Q, QElemType e) {
 QueuePtr q;
 q = new Qnode;
 if (!q) exit(OVERFLOW);
 q- data = e;
 q- next = NULL;
 Q.rear- next = q;
 Q.rear = q;
 return OK;
// 出队
Status PopLQueue(LinkQueue Q, QElemType e) {
 QueuePtr q;
 if (LQueueEmpty(Q)) return ERROR;
 q = Q.front- next;
 e = q- data;
 Q.front- next = q- next;
 if (Q.rear == q) Q.rear = Q.front;
 if (Q.rear == q) Q.rear = Q.front;
 delete q;
 return OK;
// 销毁链队列
Status DestroyQueue(LinkQueue Q) {
 while (Q.front) {
 Q.rear = Q.front- next;
 delete Q.front;
 Q.front = Q.rear;
 return OK;
// 获取队头元素
int GetHead(LinkQueue Q) {
 QElemType e;
 if (LQueueEmpty(Q)) return 0;
 e = Q.front- next- data;
 return e;
// 创建链队列
void CreateLQueue(LinkQueue Q, int m) {
 QElemType e;
 for (int i = 1; i i++) {
 cout "请输入第" i "个元素: ";
 cin e;
 PushLQueue(Q, e);
// 输出链队列
void OutPut(LinkQueue Q) {
 QueuePtr q;
 q = new Qnode;
 q = Q.front- next;
 while (q) {
 cout q- data " ";
 q = q- next;
 cout endl;
void f() {
 cout "请输入杨辉三角的阶数: ";
 int num;
 cin num;
 if (num == 1) // 行数为1
 cout 1 endl;
 else {
 cout '1' endl;
 cout "1 1" endl;
 LinkQueue q1; // 存储第i层数据
 InitLQueue(q1);
 QElemType e, q;
 // 第二行两个1
 for (int i = 0; i i++)
 PushLQueue(q1, 1);
 for (int i = 0; i num - 2; i++) {
 LinkQueue q2; // 存储第 i + 1 层
 InitLQueue(q2);
 PushLQueue(q2, 1); // 第一个数是1
 while (!LQueueEmpty(q1)) {
 PopLQueue(q1, q);
 if (LQueueEmpty(q1)) PushLQueue(q2, 1);
 else PushLQueue(q2, q + GetHead(q1));
 q1 = q2;
 OutPut(q1);
int main()
 f();
 return 0;
}
请输入杨辉三角的阶数: 5
1 2 1
1 3 3 1
1 4 6 4 1

本文转自网络,原文链接:https://developer.aliyun.com/article/787398
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:手把手教你在SpringCloud alibaba中集成ELK 下一篇:没有了

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐