#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<stdbool.h>
#define TRUE 1
#define FALSE 0
using namespace std;
typedef int QueueElemType;
typedef struct node {
QueueElemType data;
struct node *next;
}LinkQueueNode;
typedef struct {
LinkQueueNode * front;
LinkQueueNode *rear;
}LinkQueue;
int InitLinkQueue(LinkQueue *Q) {
Q->front = (LinkQueueNode *)malloc(sizeof(LinkQueueNode));
if (Q->front) {
Q->rear = Q->front;
Q->front->next = NULL;
return TRUE;
}
else
return FALSE;
}
int IsEmpty(LinkQueue Q)
{
return Q.front->next == NULL;
}
int EnterQueue(LinkQueue *Q, QueueElemType x)
{
LinkQueueNode *p;
p = (LinkQueueNode*)malloc(sizeof(LinkQueueNode));
if (p) {
p->data = x;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
return TRUE;
}
else
return FALSE;
}
int DeleteQueue(LinkQueue *Q, QueueElemType *x)
{
if (Q->rear == Q->front)
return FALSE;
LinkQueueNode * p;
p = Q->front->next;
Q->front->next = p->next;
if (Q->rear == p)
Q->rear = Q->front;
*x = p->data;
free(p);
return TRUE;
}
int GetHead(LinkQueue *Q, QueueElemType *x) {
if (Q->front->next == NULL) {
return FALSE;
}
*x = Q->front->next->data;
return TRUE;
}
int ClearQueue(LinkQueue *Q) {
LinkQueueNode * p = Q->front->next, *temp;
Q->front->next = NULL;
Q->rear = Q->front;
while (p) {
temp = p->next;
free(p);
p = temp;
}
return TRUE;
}
void YangHuiTrianglePrint(int n)
{
LinkQueue Q;
InitLinkQueue(&Q);
EnterQueue(&Q, 1);
int temp, head,sum;
for (int i = 2; i <= n; i++) {
for (int k = 1; k <= n - i + 1; k++) {
cout << " ";
}
EnterQueue(&Q, 1);
for (int j = 1; j <= i - 2; j++) {
DeleteQueue(&Q, &temp);
cout << temp<<" ";
GetHead(&Q, &head);
sum = temp + head;
EnterQueue(&Q, sum);
}
DeleteQueue(&Q, &temp);
cout << temp;
cout << endl;
EnterQueue(&Q, 1);
}
while (!IsEmpty(Q)) {
DeleteQueue(&Q, &temp);
cout << temp<<" ";
}
cout<< endl;
}
int main()
{
YangHuiTrianglePrint(8);
return 0;
}
|