用循环队列解决杨辉三角
#include <stdio.h>#include <stdlib.h>
#define Maxsize 10
typedef struct NODE
{
int data[Maxsize];
int rear;
int front;
}CqQueue, *Cqlist;
/*
函数功能:队列的初始化
*/
Cqlist InitCQ(Cqlist Queue)
{
Queue = (Cqlist)malloc(sizeof(CqQueue));
if (!Queue)
{
printf("Memory allocation is failure!\n");
}
Queue->front = 0;
Queue->rear = 0;
return Queue;
}
/*
函数功能:从队头删除元素
*/
Cqlist DeleteQueue(Cqlist Queue, int *temp)
{
if (Queue->rear == Queue->front)
return Queue;
Queue->front = (Queue->front + 1) % Maxsize;//(Queue->front + 1)%Maxsize, (Queue->rear + 1) % Maxsize; 形成循环队列
*temp = Queue->data[Queue->front];
Queue->data[Queue->front] = 0;
return Queue;
}
/*
函数功能:查找队头元素
*/
Cqlist GetHeadQueue(Cqlist Queue, int *x)
{
if (Queue->rear == Queue->front)
return Queue;
*x = Queue->data[(Queue->front + 1) % Maxsize];
return Queue;
}
/*
函数功能:从队尾插入元素
*/
Cqlist EnterQueue(Cqlist Queue, int e)
{
Queue->rear = (Queue->rear + 1) % Maxsize;
if (Queue->rear == Queue->front)
printf ("The queue is full !");
else
Queue->data[Queue->rear] = e;
return Queue;
}
/*
函数功能:打印杨辉三角
*/
void PascalTriangle(Cqlist Queue, int len)
{
int temp, x, L, n;
Queue = InitCQ(Queue);
Queue = EnterQueue(Queue, 1);
for (n=2; n<=len; n++)
{
Queue = EnterQueue(Queue, 1);
for (L=1; L<=n-2; L++)
{
Queue = DeleteQueue(Queue, &temp);
printf("%d\t", temp);
Queue = GetHeadQueue(Queue, &x);
temp = temp + x;
Queue = EnterQueue(Queue, temp);
}
Queue = DeleteQueue(Queue, &temp);
printf("%d\t", temp);
printf("\n");
Queue = EnterQueue(Queue, 1);
}
while (Queue->rear != Queue->front)
{
Queue = DeleteQueue(Queue, &temp);
printf("%d\t", temp);
}
printf("\n");
}
int main(void)
{
Cqlist Queue;
int len;
printf("please input the size of the pascal triangle:\n");
scanf ("%d" , &len);
PascalTriangle(Queue, len);
return 0;
}