#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; } Status print(SqQueue *Q, int Qsize) { int i; if (Q->rear == Q->front) return ERROR; i = Q->front; printf("%*c", 3 * (Qsize - getlength(Q, Qsize)), ‘ ‘); while (i != Q->rear) { printf(" %*d", (i + Qsize) / Qsize > 1 ? -5 : 5, Q->base[i]); i = (1 + i) % Qsize; } printf("\n"); return OK; } void yanghuisanjiao(SqQueue *Q, int n) { // 1 // 1 1 // 1 2 1 // 1 3 3 1 int Qsize = n + 1; int i; printf("%d行的杨辉三角\n", n); InitQueue(Q, Qsize); 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] == 1) break; } EnQueue(Q, Qsize, 1); print(Q, Qsize); } } int main(void) { int n; SqQueue Q; puts("循环队列实现杨辉三角的计算:"); puts("请输入有多少行? (为了观察建议20以内)"); scanf("%d", &n); yanghuisanjiao(&Q, n); return 0; }
时间: 2024-12-21 00:19:41