#include <stdio.h> #include <malloc.h> #define OK 1 #define OVERFLOW -1 #define ERROR 0 typedef int Status, QElemType; //队列结构定义 typedef struct { QElemType *base; int front; int rear; } SqQueue; //初始化队列 Status InitQueue(SqQueue *Q, int Qsize) { Q->base = (QElemType *)malloc(Qsize * sizeof(QElemType)); if (!Q->base) return OVERFLOW; Q->front = Q->rear = 0; return OK; } //入队 Status EnQueue(SqQueue *Q, int Qsize, QElemType e) { if ((Q->rear + 1) % Qsize == Q->front) return ERROR; Q->base[Q->rear] = e; Q->rear = (Q->rear + 1) % Qsize; return OK; } //取队长 int getlength(SqQueue *Q, int Qsize) { return (Q->rear - Q->front + Qsize) % Qsize; } //出队 Status DeQueue(SqQueue *Q, int Qsize) { if (Q->front == Q->rear) return ERROR; Q->front = (Q->front + 1) % Qsize; return OK; } //显示两个0之间的数字 Status print(SqQueue *Q, int Qsize) { // 0 1 0 // 0 1 1 0 // 0 1 2 1 0 // 0 1 3 3 1 0 int i; if (Q->rear == Q->front) return ERROR; printf("%*c", 3 * (Qsize - getlength(Q, Qsize)), ' '); i = (Q->front + 1) % Qsize; while ((1 + i) % Qsize != Q->rear) { printf(" %*d", (i + Qsize) / Qsize > 1 ? -5 : 5, Q->base[i]); i = (1 + i) % Qsize; } printf(" "); return OK; } //杨辉三角 void yanghuisanjiao(SqQueue *Q, int n) { int Qsize; int i; printf("%d行的杨辉三角 ", n); Qsize = n + 3; InitQueue(Q, Qsize); EnQueue(Q, Qsize, 0); EnQueue(Q, Qsize, 1); for ( i = 1; i <= n; i++ ) { while ( getlength(Q, Qsize) > 2 ) { EnQueue(Q, Qsize, Q->base[Q->front] + Q->base[(Q->front + 1) % Qsize]); DeQueue(Q, Qsize); if (Q->base[Q->front] == 0) break; } EnQueue(Q, Qsize, 0); print(Q, Qsize); } } //主函数 int main(void) { int n; SqQueue Q; puts("循环队列实现杨辉三角的计算:"); puts("请输入有多少行? (为了观察建议20以内)"); scanf("%d", &n); yanghuisanjiao(&Q, n); return 0; }