循环队列打印杨辉三角

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<iomanip>
#include<queue>

typedef long long ll;
const int inf = 0x3f3f3f3f;

using namespace std;

#define maxsize 600

typedef struct{
    int *base;
    int front,rear;
}que;

int init(que &q){

    q.base = (int *)malloc(sizeof(int) * maxsize);
    if(!q.base)
    {
        printf("分配内存失败!\n");
        return 0;
    }

    else
    {

        q.front = 0;
        q.rear = q.front;
        return 1;
    }

}

int push(que &q,int val){

    if(q.rear + 1 % maxsize == q.front)
    {
        printf("队列已满!\n");
        return 0;
    }

    else
    {

        q.base[q.rear] = val;
        q.rear = (q.rear + 1) % maxsize;

        return 1;
    }

}

int pop(que &q,int &val){

    if(q.front == q.rear)
    {
        printf("队列为空!\n");
        return 0;
    }

    else
    {

        val = q.base[q.front];
        q.front = (1 + q.front) % maxsize;

        return 1;
    }

}

int main(){

    que q;
    init(q);

    int n,temp,now;
    scanf("%d",&n);
    push(q,1);    //将第一行的1入队

    for(int i = 2;i <= n;i++)    //从第二行到第n行的入队操作,以及打印第i - 1行的所有元素
    {

        push(q,1);        //每一行的第一个元素
        for(int j = 1;j <= i - 2;j++)    //求第2个到i - 1个元素的值
        {

            pop(q,temp);
            printf("%-3d ",temp);        //打印上一行的元素    执行i - 2次循环 而上一行有i - 1个元素
            now = q.base[q.front];
            push(q,now + temp);

        }

        pop(q,temp);        
        printf("%-3d\n",temp);        //打印上一行的最后一个元素
        push(q,1);            //将本行的最后一个元素入队
    }

    for(int i = 1;i <= n;i++)        //打印第n行元素
    {
        pop(q,temp);
        printf("%-3d ",temp);
    }
    printf("\n");

    free(q.base);

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值