zoukankan      html  css  js  c++  java
  • 打印杨辉三角

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

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

    因此在这里分享一下,也同时方便以后欣赏欣赏 , 下面的代码使用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
    ");
        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(" "); } } int main(){ int inp; printf("enter the low:"); scanf("%d",&inp); YangHui(inp); return 0; }

  • 相关阅读:
    java 问题记录
    java 构造方法
    java 接口
    java 抽象类
    java 封装
    java 面向对象
    java 集合小练习 超市库存管理系统
    linux常用指令
    个人简历表格
    html5 表格文档常用指令
  • 原文地址:https://www.cnblogs.com/demonxian3/p/7426716.html
Copyright © 2011-2022 走看看