数据结构:使用栈和队列相关知识打印杨辉三角

本文利用数据结构队列知识编程实现打印杨辉三角,源代码如下:

#include <stdio.h>

 

#define MAXSIZE 50

#define N 10

 

typedef int QueueElementType;

 

typedef struct

{

    QueueElementType element[MAXSIZE];

    int front;

    int rear;

}SeqQueue;

 

void InitQueue(SeqQueue *Q)

{

    Q->front = Q->rear = 0;

}

void EnterQueue(SeqQueue *Q, QueueElementType x)

{

    if ((Q->rear + 1) % MAXSIZE == Q->front)

    {

        printf("队列已满不能入队\n");

        return;

    }

    Q->element[Q->rear] = x;

    Q->rear = (Q->rear + 1) % MAXSIZE;

}

void printQ(SeqQueue Q)

{

    int i;

    i = Q.front;

    while (i != Q.rear)

    {

        if (i == MAXSIZE)

        {

            i = 0;

        }

        printf(" %d ", Q.element[i]);

        i++;

    }

    printf("\n");

}

 

void DeleteQueue(SeqQueue *Q, QueueElementType *x)

{

    if (Q->front == Q->rear)

    {

        printf("队列为空不能出队\n");

        return;

    }

    *x = Q->element[Q->front];

    Q->front = (Q->front + 1) % MAXSIZE;

}

void GetHead(SeqQueue *Q, QueueElementType *x)

{

    if (Q->front == Q->rear)

    {

        printf("队列为空不能取值\n");

        return;

    }

    *x = Q->element[Q->front];

}

 

void main()

{

    SeqQueue Q;

    QueueElementType x, temp;

    int n;

    int i;

    InitQueue(&Q);

 

    EnterQueue(&Q, 1);//第一行元素入队

    for (n = 2; n <= N; n++)//产生第n行元素并入队,同时打印第n-1行的元素

    {

        EnterQueue(&Q, 1);//第n行的第一个元素入队

        for (i = 1; i <= n - 2; i++)//利用队中第n-1行元素产生第n行的中间n-2个元素并入队

        {

            DeleteQueue(&Q, &temp);

            printf(" %d ", temp);//打印第n-1行的元素

            GetHead(&Q, &x);

            temp = temp + x;//利用队中第n-1行元素产生第n行元素

            EnterQueue(&Q, temp);

        }

        DeleteQueue(&Q, &x);

        printf(" %d ", x);//打印第n-1行的最后一个元素

        EnterQueue(&Q, 1);//第n行的最后一个元素入队

        printf("\n");

    }

    while (Q.front != Q.rear)//打印最后一行元素

    {

        DeleteQueue(&Q, &x);

        printf(" %d ", x);

    }

 

}



本段代码利用数据结构打印出杨辉三角前10行,如果想要打印其他行数只需将代码最开始的宏定义  #define N 10  中的10改为其他值即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值