菜鸟练习PAT(二)

题目标号:A-1002

这个题目在最后提交的时候总是最后几个测试点过不了,有了前一次的经验,猜到肯定是特殊情况没有考虑进去。最后排查到,是当系数为0时,那个阶数也打印出来了大哭。调整了一下,再最后获取总的个数时,浪费了点时间把它的非零值装入了一个链表里了。

题目:


菜鸟代码:

#include "stdio.h"
#include "stdlib.h"

typedef struct Node
{
	int N;
	float an;
	struct Node *node;
}Num ;

int insertNum(Num *head ,  int N  , float an )
{

	Num * node ;
	Num * hnode = head ; 
	
	if(head->N == -1)
	{
		hnode->an = an ;
		hnode->N = N ;

		return 1 ;
	}

	while(hnode->node != NULL)
	{
		if( hnode->N == N )
		{
			hnode->an = hnode->an + an ;
			return 0;
		}

		hnode = hnode->node ;
	}
	
	if( hnode->N == N )
	{
		hnode->an = hnode->an + an ;
		return 0;
	}

	node = (Num*)malloc(sizeof(Num)) ;
	node->an = an;
	node->N = N;
	node->node = NULL ;	

	hnode = head;
	
	while(hnode->node != NULL)
	{
		if( node->N > hnode->N )
		{
			Num *temp = (Num*)malloc(sizeof(Num)) ;

			temp->N = hnode->N ;
			temp->an = hnode->an;
			hnode->N = node->N ;
			hnode->an = node->an;
			node->N = temp->N ;
			node->an = temp->an ;
		}

		hnode = hnode->node ;
	}

	if( node->N > hnode->N )
	{
		Num temp = *hnode;
		*hnode = *node ;
		*node = temp ;
	}

	hnode->node = node;
	
	return 0;
}

Num * getCount(Num *n)
{
	int count = 0;
	Num *index = n;
	Num *store = (Num *)malloc(sizeof(Num));
	Num *search = store ;
	store->node = NULL ;

	while( index != NULL)
	{
		if(index->an != 0)
		{
			Num *node = (Num *)malloc(sizeof(Num));
			count++;
	
			node->an = index->an;
			node->N = index->N;
			node->node = NULL ;
			store->node = node ;
			store= node ;
			
		}
		index = index->node ;
	}
	
	search->N = count ;

	return search;
}

void showNum(Num * n)
{	
	Num * data = getCount(n) ;
	
	if(data->N == 0)
	{
		printf("0\n");
		return;
	}else
	{
		printf("%d " ,data->N );
		data = data->node;
	}
	
	while(data->node != NULL)
	{
		printf("%d %.1f " , data->N ,data->an);
		data = data->node;
	}
	
	printf("%d %.1f\n" , data->N ,data->an);	
}

Num * initNum(Num * n)
{
	n->an = 0;
	n->N = -1;
	n->node = NULL;

	return n;
}

int main(void)
{
	int count = 2;

	Num *dnum ;
	Num *head = (Num*)malloc(sizeof(Num));

	head = initNum(head);
	dnum = head;
	while(count--)
	{
		int num ;
		
		scanf("%d" , &num);
		while(num--)
		{
			int temp ;
			float data = 0.0;
		
			scanf("%d %f" , &temp , &data);
			
			temp =  insertNum( head , temp , data ) ;
		}
	}

	showNum(head);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值