利用循环队列打印杨辉三角(c语言实现)

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

#define MAXQSIZE 200
typedef int QElemType;
typedef struct {
    QElemType  *base;
    int front;
    int rear;
}SqQueue;
void InitQueue(SqQueue *Q){
    //构造一个空队列Q
    Q->base=(QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
    if(!Q->base)exit(1);
    Q->front=Q->rear=0;
}
int QueueLength(SqQueue *Q){
    //返回Q的元素个数,即队列的长度
    int e;
    e=(Q->rear-Q->front+MAXQSIZE)%MAXQSIZE;
    return e;
}
void EnQueue(SqQueue *Q,QElemType e){
    //插入的元素e为Q的新的队尾元素
    if((Q->rear+1)%MAXQSIZE ==Q->front) exit(1);
    Q->base[Q->rear]=e;
    Q->rear=(Q->rear+1)%MAXQSIZE;
}
void DeQueue(SqQueue *Q){
    //若队列不空,则删除Q的队头元素,用e返回其值
    if(Q->front==Q->rear)
        exit(1);
    //e=Q.base[Q.front];
    Q->front=(Q->front+1)%MAXQSIZE;
}
QElemType GetHead(SqQueue *Q){
    //返回队头元素
    return Q->base[Q->front];
}
int main(){
    int N,n,c;
    QElemType t,x;
    SqQueue f,*Q;
    Q=&f;
    InitQueue(Q);
    printf("请输入杨辉三角规模:\n");
    scanf("%d",&N);
    EnQueue(Q,1);
    for(n=2;n<=N;n++){
        EnQueue(Q,1);
        for(c=1;c<=n-2;c++){
            t=GetHead(Q);
            DeQueue(Q);
            printf("%4d",t);
            x=GetHead(Q);
            t=t+x;
            EnQueue(Q,t);   
        }
        EnQueue(Q,1);
        printf("%4d",GetHead(Q));
        DeQueue(Q);
        printf("\n");
    }
    while(Q->front!=Q->rear){
            printf("%4d",GetHead(Q));
            DeQueue(Q);
        }
    return 0;
    }

这里写图片描述

  • 27
    点赞
  • 129
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值