[C语言、C++]数据结构作业:用队列打印杨辉三角

 

 

 

 

#include <iostream>
using namespace std;
typedef int ElemType; //元素的数据类型
struct QueueNode { //队列结点定义
    ElemType data;
    QueueNode* next;
};
struct LinkQueue { //队列结构定义
    QueueNode* rear,
        * front; //队尾与队头指针
};
void InitQueue(LinkQueue& Q) {
    Q.rear = Q.front = NULL;
}
bool IsEmpty(const LinkQueue& Q) {
    return Q.front == NULL;
}
bool getFront(const LinkQueue& Q, ElemType& e) {
    if (IsEmpty(Q))
        return false;
    e = Q.front->data;
    return true;
}
int EnQueue(LinkQueue& Q, ElemType e) {
    QueueNode* s = new QueueNode;
    s->data = e; s->next = NULL;//创建结点
    if (!Q.front) //空
        Q.front = Q.rear = s; //f,r指向首元节点
    else { //不空
        Q.rear->next = s; //尾插
        Q.rear = s;
    }
    return 1;
}
int DeQueue(LinkQueue& Q, ElemType& e) {
    //删去队头结点,并返回队头元素的值
    if (IsEmpty(Q)) return 0;//判队空
    QueueNode* q = Q.front;
    e = q->data; //保存队头的值
    Q.front = Q.front->next; //新队头
    if (Q.front == NULL) Q.rear = NULL;
    delete q;
    return 1;
}
void Triangle(int n){
    LinkQueue Q; InitQueue(Q);int e; int q;
    EnQueue(Q, 1);
    for (int i = 2; i <= n; i++) {
        EnQueue(Q, 1);
        for (int j = 1; j <= i-2; j++) {
            DeQueue(Q, e);
            cout << e;
            getFront(Q, q);
            e = e + q;
            EnQueue(Q, e);
        }
        DeQueue(Q, q);
        cout << q;
        EnQueue(Q, 1);
        cout << endl;
    }
    while (!IsEmpty(Q)) {
        DeQueue(Q, q);
        cout << q;
    }
}
int main(){
    int n;
    cout << "请输入打印行数:";
    cin >> n;
    cout << "===============" << endl;
    Triangle(n);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值