用鏈表實現多項式的相加

還有些小BUG望共同完善
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _datatype_ {
	int coef;
	int exp;
}datatype;

typedef struct _linklist_ {
	datatype data;
	struct _linklist_ *next;
}linknode;


linknode *creat_node(datatype data)
{
	linknode *p = (linknode *)malloc(sizeof(linknode));
	memset(p,0,sizeof(linknode));
	p->data.coef = data.coef;
	p->data.exp = data.exp;
	return p;
}

void insert_data(linknode *head, datatype data)
{
	linknode *new = NULL;
	if(NULL == head)
		return ;
	new = creat_node(data);
	while(head->next != NULL && head->next->data.exp < data.exp)
		head = head->next;
	new->next = head->next;
	head->next = new;
}

void get_data(linknode *head)
{
	datatype data = {0};
	if(NULL == head)
		return ;
	while(1)
	{
		scanf("%d,%d",&data.coef,&data.exp);
		if(0 == data.coef)
			break;
		insert_data(head,data);
	}
}

void show_data(linknode *head)
{
	if(NULL == head)
		return ;
	while(head->next != NULL)
	{
		head = head->next;
		printf(" %dx^%d +",head->data.coef,head->data.exp);	
	}
	putchar(8);
	putchar(32);
	putchar(10);
	return ;
}

void combine_list(linknode *pa, linknode *pb, linknode *pc)
{
	linknode *pre = NULL;
	linknode *pc_bk = pc;
	if( NULL == pa || NULL == pb || NULL == pc )
		return ;
	pa = pa->next;
	pb = pb->next;

	while(pa != NULL && pb != NULL)
	{
		/**********  BUG :::::   **********/
#if 1
		if(pre != NULL && pre->data.exp == pc->data.exp && pre != pc_bk)
		{
			pre->data.coef += pc->data.coef;
			pre->next = NULL;
			free(pc);
			pc = pre;
		}
#endif
		if(pa->data.exp < pb->data.exp )
		{
			pc->next = creat_node(pa->data);
			pa = pa->next;
		}
		else if (pa->data.exp == pb->data.exp)
		{
			pc->next = creat_node(pa->data);
			pc->next->data.coef  += pb->data.coef;
			pa = pa->next;
			pb = pb->next;
		}
		else
		{
			pc->next = creat_node(pb->data);
			pb = pb->next;
		}

		pre = pc;
		pc = pc->next;
	}
	while(pa != NULL)
	{
		pc->next = creat_node(pa->data);
		pc = pc->next;
		pa = pa->next;
	}
	while(pb != NULL)
	{
		pc->next = creat_node(pb->data);
		pc = pc->next;
		pb = pb->next;
	}
}

int main()
{
	datatype data = {0};
	linknode *pa = creat_node(data);
	linknode *pb = creat_node(data);
	linknode *pc = creat_node(data);

	puts("input data of pa:");
	get_data(pa);
	puts("input data of pb:");
	get_data(pb);
	puts("show data :");
	show_data(pa);
	show_data(pb);
	combine_list(pa,pb,pc);
	puts("show data of pc:");
	show_data(pc);
	return 0;
}
相關文章
相關標籤/搜索