打印杨辉三角

打印杨辉三角的数据结构使用的是队列,下面的代码设计的很巧妙

对于新手的我来说设计难度还是比较大,想了半天想不出来

因此在这里分享一下,也同时方便以后欣赏欣赏 , 下面的代码使用C语言实现...

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

#define OK 1

typedef int ElemType;
typedef int Status;
typedef struct Qnode{
  ElemType data;
  struct Qnode *next;
}Qnode,*Qlink;

typedef struct {
  Qlink front;
  Qlink rear;
} Queue;

Status initQueue(Queue *Q){
  Q->front = Q->rear = (Qlink)malloc(sizeof(Qnode));
  Q->front->next = NULL;
  return OK;
}

Status enQueue(Queue *Q,ElemType e){
  Qlink new = (Qlink)malloc(sizeof(Qnode));
  new->data = e;
  new->next = NULL;

  Q->rear->next = new;
  Q->rear = new;
  return OK;
}

Status deQueue(Queue *Q,ElemType *e){
  if(Q->front == Q->rear){
    printf("overflow\n");
    exit(1);
  }

  Qlink tmp = Q->front->next;
  *e = tmp->data;
  Q->front->next = tmp->next;
  if(tmp == Q->rear)Q->rear = Q->front;
  free(tmp);
  return OK;
}

Status getHead(Queue Q,ElemType *e){
  if(Q.front->next == NULL) *e=-2;
  *e = Q.front->next->data;
  return OK;
}

void YangHui(int num){
  int i,j,p,s,e;
Queue Q; initQueue(
&Q); enQueue(&Q,1);
for(i=1;i<=num;i++){ s=0; enQueue(&Q,1); for(j=1;j<=i+1;j++){ getHead(Q,&p); printf("%4d",p); deQueue(&Q,&e); enQueue(&Q,s+p); s=p; } printf("\n"); } } int main(){ int inp; printf("enter the low:"); scanf("%d",&inp); YangHui(inp); return 0; }

 

 

转载于:https://www.cnblogs.com/demonxian3/p/7426716.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值