C++ 队列实现杨辉三角形

记录一下数据结构的第一篇博客——用队列实现输出杨辉三角形的前n行。

杨辉三角形是二项式 (a+b)^n 展开式的系数,直观而言,第一行是1,从第二行开始,每个数字等于它斜上方两个数字和。

我们要利用队列先进先出的特性,对其内的数字进行求和操作,并输出作为杨辉三角形的参数。

#include<iostream>
using namespace std;

typedef int ElemType;

typedef struct LinkNode {
    ElemType data;
    struct LinkNode* next;
}LinkNode;

typedef struct {  // 或写作typedef struct LinkQueue{}
    LinkNode* front, * rear;
}LinkQueue;

// 初始化队列
bool InitQueue(LinkQueue& Q) {
    Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
    return true;
}

// 入队
void EnQueue(LinkQueue& Q, ElemType x) {
    LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
    if (!s)cout << "Invalid value!" << endl;  // 判空
    else s->data = x;
    Q.rear->next = s;
    Q.rear = s;
}

// 出队
bool DeQueue(LinkQueue& Q, ElemType& x) {
    if (Q.front == Q.rear) return false;
    LinkNode* p = Q.front->next;
    x = p->data;
    Q.front->next = p->next;
    if (Q.rear == p)Q.rear = Q.front;
    free(p);
    return true;
}

int main() {
    LinkQueue Q;
    InitQueue(Q);
    
    int n, x;
    cin >> n;

    EnQueue(Q, 1);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < i; j++) {
            int left = Q.front->next->data;
            DeQueue(Q, x);
            cout << x;
            int right = Q.front->next->data;
            EnQueue(Q, left + right);
        }
        cout << 1 << endl;
        EnQueue(Q, 1);
    }
    system("pause");
    return 0;
}

运行结果:以6为例:

  • 10
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值