使用队列,打印杨辉三角

#include <stdlib.h>
#include <stdio.h>
#include "Conio.h"
#define MAX 15
#define LINE  10
typedef int ElemType;
typedef struct
{
   ElemType data[ MAX ];
   int front,rear;
}SqQueue;
SqQueue* InitQueue()
{
    SqQueue* q;
    q=(SqQueue*)malloc(sizeof(SqQueue));
    q->front=q->rear=0;
    return q;
}
void EnQueue(SqQueue* q,ElemType x)
{
    if((q->rear+1)% MAX == q->front) exit(1);
    q->data[q->rear]=x;
    q->rear=(q->rear+1)% MAX;
}
ElemType DeQueue(SqQueue* q)
{
    ElemType x;
    if(q->front == q->rear) exit(1);
       x=q->data[q->front];
    q->front=(q->front+1)% MAX;
    return x;
}
int QueueEmpty(SqQueue* q)
{
    return (q->front==q->rear);
}
ElemType GetHead(SqQueue* q)
{
    ElemType x;
    if(q->front == q->rear) return 0;
    else
    x=q->data[q->front];
    return x;
}
void TraversalSq(SqQueue q)
{
   do
   {
     printf("%d  ",DeQueue(&q));
   }
   while(!QueueEmpty(&q));
}
void YangHui(int n)
{
   SqQueue* q;
   int i,j,s,t;
   printf("1\n");
   q=InitQueue();
   EnQueue(q,0);
   EnQueue(q,1);
   EnQueue(q,1);
   for(j=1;j<=n;j++)
   {
       EnQueue(q,0);
       do{
        s= DeQueue(q);
        t= GetHead(q);
        if(t) printf("%d  ",t);
        else printf("\n");
        EnQueue(q,s+t);
       }while(t!=0);
   }
    DeQueue(q);
    TraversalSq(*q);
}
int main(void)
{
   YangHui(LINE);
   getch();
   return 0;
}

0

Leave a Reply

Your email address will not be published.