杨辉三角

基于队列的杨辉三角

#include<iostream>
using namespace std;

#define MAXSIZE 100

typedef int QueueElemType;
typedef struct
{
    QueueElemType elem[MAXSIZE];
    int front;
    int rear;
}SeqQueue;

void InitQueue(SeqQueue &Q);
bool Isempty(SeqQueue Q);
bool Isfull(SeqQueue Q);
void EnQueue(SeqQueue &Q, QueueElemType e);
void DelQueue(SeqQueue &Q, QueueElemType &e);
void Gethead(SeqQueue Q, QueueElemType &e);
void YangHuiTriangle();

int main()
{
    YangHuiTriangle();
    cout << endl;
    return 0;
}

void InitQueue(SeqQueue &Q)
{
    Q.front = Q.rear = 0;
}

bool Isempty(SeqQueue Q)
{
    if (Q.rear == Q.front)
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool Isfull(SeqQueue Q)
{
    if ((Q.rear + 1) % MAXSIZE == Q.front)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void EnQueue(SeqQueue &Q, QueueElemType e)
{
    if (Isfull(Q))
    {
        cout << "队列已满!" << endl;
    }
    else
    {
        Q.elem[Q.rear] = e;
        Q.rear = (Q.rear + 1) % MAXSIZE;
    }
}

void DelQueue(SeqQueue &Q, QueueElemType &e)
{
    if (Isempty(Q))
    {
        cout << "队列为空!" << endl;
    }
    else
    {
        e = Q.elem[Q.front];
        Q.front = (Q.front + 1) % MAXSIZE;
    }
}

void Gethead(SeqQueue Q, QueueElemType &e)
{
    if (Isempty(Q))
    {
        cout << "队列为空!" << endl;
    }
    else
    {
        e = Q.elem[Q.front];
    }
}

void YangHuiTriangle()
{
    int N;
    cout << "请输入N:";
    cin >> N;
    cout << "杨辉三角前" << N << "行:" << endl;
    SeqQueue Q;
    InitQueue(Q);
    QueueElemType temp, x;
    EnQueue(Q, 1);
    for (int n = 2; n <= N; n++)
    {
        EnQueue(Q, 1);
        for (int j = 0; j <= N - n; j++)
            cout << " ";
        for (int i = 1; i <= n - 2; i++)
        {
            DelQueue(Q, temp);
            cout << temp << "  ";
            Gethead(Q, x);
            temp += x;
            EnQueue(Q, temp);
        }
        DelQueue(Q, x);
        cout << x << endl;
        EnQueue(Q, 1);
    }
    while (!Isempty(Q))
    {
        DelQueue(Q, x);
        cout << x << "  ";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值