用队列打印杨辉三角

用队列打印杨辉三角

/*
*filename: yanghui_print.c
*author: Bob
*version: v1.0
*time: 2014-10-24
*/
#include<stdio.h>
#include<stdlib.h>

typedef struct node  
{
	int data;
    struct node *next;
}Node;

typedef struct linkqueue  
{
	Node *front;
	Node *rear;
}Linkqueue;

void init_queue(Linkqueue *q)     
{
	Node *p = (Node *)malloc(sizeof(Node)); 
	if(p==NULL)
	{
		printf("malloc failed\n");
		return ;
	}
	 q->front = q->rear = p;
	 q->rear->next = NULL;
}

void queue_in(Linkqueue *q,int num)    
{
	Node *p = (Node *)malloc(sizeof(Node));
	if(p==NULL)
	{
		printf("malloc failed\n");
		return ;
	}

	 p->data = num;
	 p->next = NULL;
	 q->rear->next = p;
	 q->rear = p;
}

int queue_out(Linkqueue *q)  
{
	int x;
	Node *p = NULL;
	if(q->front == q->rear) 
	{
		printf("NULL");
		return -1;
	}
	else
	{   // x = q->front->next->data;
		 p = q->front->next;
		 x = p->data;
		 q->front->next = p->next;
		 free(p);    

		if(q->front->next == NULL)	
		{
			q->rear = q->front;
		}
		return x;
	}
}

void yanghui_print(int n)   
{
	int i=0,j=0;
	int a=0,b=0;
	Linkqueue *q = (Linkqueue *)malloc(sizeof(Linkqueue));
	if(q == NULL)
	{
		printf("malloc failed\n");
		return ;
	}

	if(n<=0) 
	{
		printf("error\n");
		return ;
	 }
	else
	{
		init_queue(q);
		//for(i=1;i<n;i++)
		//{
		//	printf("   ");    
		//}
	    printf("1\n");
		queue_in(q,1);

		for(i=2;i<=n;i++)
		{
			//for(j=1;j<n-i+1;j++)
			//{
			//	printf("   ");
			//}

			a = 0;
			for(j=1;j<i;j++)
			{
				b = queue_out(q);
				printf("%d  ",a+b);
				queue_in(q,a+b);
				a=b;
			}
			printf("1\n");
			queue_in(q,1);
		}
	}
}

void main()
{
	int n;
	printf("Please input lines you want to print:");
    <span style="white-space:pre">	</span>scanf("%d",&n);
    <span style="white-space:pre">	</span>yanghui_print(n);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值