用队列存放数组(指针),打印杨辉三角

直接上代码: 

#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct Node {
    // 结点
    int *data;
    struct Node *next;
} Node;

typedef struct {
    // 定义一个队列,包含头指针和尾指针
    Node *front;
    Node *rear;
} Queue;

int initQueue(Queue &Q) {
    // 初始化队列,令头指针等于尾指针
    Q.front = Q.rear = (Node *) malloc(sizeof(Node));
    if (!Q.front)
        exit(-2);
    Q.front->next = nullptr;
    return 0;
}

int enQueue(Queue &Q, int *e) {
    // 插入元素e为Q的新的队尾元素
    Node *p = (Node *) malloc(sizeof(Node));
    if (!p)
        exit(-2);
    p->data = e;
    p->next = nullptr;
    Q.rear->next = p;
    Q.rear = p;
    return 1;
}

int deQueue(Queue &Q, int **e) {
    // 若队列不空,则删除Q的队头元素,用e返回其值,并返回1;否则返回0
    if (Q.front == Q.rear)
        return 0;
    Node *p = Q.front->next;
    *e = p->data;
    Q.front->next = p->next;
    if (Q.rear == p)
        Q.rear = Q.front;
    free(p);
    return 1;
}

void print_YangHui_Triangle(int n) {
    Queue Q;
    initQueue(Q);
    for (int i = 1; i < n + 1; i++) {
        int *arr = new int[i];
        if (i == 1)
            arr[0] = 1;
        else {
            for (int j = 1; j < i + 1; j++) {
                if (j == 1 || j == i)
                    arr[j - 1] = 1;
                else {
                    arr[j - 1] = Q.rear->data[j - 1] + Q.rear->data[j - 2];
                }
            }
        }
        enQueue(Q, arr);
    }
    for (int i = 1; i < n + 1; i++) {
        int *arr;
        deQueue(Q, &arr);
        for (int j = 0; j < i; j++) {
            cout << arr[j] << ' ';
        }
        cout << endl;
    }
}

int main() {
    print_YangHui_Triangle(3);
    cout << endl;
    print_YangHui_Triangle(5);
    cout << endl;
    print_YangHui_Triangle(10);
}

运行结果: 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值