数据结构:一元多项式表示及相加的完整代码

  • 时间:
  • 浏览:
  • 来源:互联网

一元多项式表示及相加的完整代码是一个链表应用的例子。下面给出了完整的代码,在VC++ 6.0以及 Dev-C++ 下编译通过。

测试数据:

A多项式输入:

7 0

3 1

9 8

5 17

0 0

B多项式输入:

8 1

22 7

-9 8

0 0

输出:

#include "stdio.h"
#include "malloc.h"
#include "math.h"
typedef struct LNode
{
	float	coef;
	int	exp;
	struct	LNode *next;
}LNode, *PolyList ;
PolyList addpoly(PolyList head1, PolyList head2)
{        PolyList	pa,pb,pre_pa,next_pb;
	float sum;
	pa=head1->next;  
	pb=head2->next;  
	pre_pa=head1;       //pre_pa为pa的前驱
	while (pa&&pb)
	{
		if (pa->exp<pb->exp)
		{
			pre_pa=pa;
			pa=pa->next;   
		}
		else if (pa->exp>pb->exp)
		{
			next_pb=pb->next;     
			pre_pa->next=pb;
			pb->next=pa;
			pre_pa=pb;          
			pb=next_pb;
		}
		else if (pa->exp==pb->exp)
		{	sum=pa->coef+pb->coef;
			if (sum!=0)
			{	pa->coef=sum;
				pre_pa=pa;
				pa=pa->next;
			}
			else
			{	pre_pa->next=pa->next;  
				free(pa);
				pa=pre_pa->next;
			}
			next_pb=pb->next;      
			free(pb);   pb=next_pb;
		}
	}
	if(pb)	pre_pa->next=pb;   
	free(head2);  
	return(head1);
}
void PrintPoly(PolyList head)
{
	PolyList p;
	p=head->next;
	while(p)
	{
		printf("%2.2fx%2d  +  ",p->coef,p->exp);
		p=p->next;
	}
	printf("\n");
}
void CreatePoly(PolyList &L)
{
	int exp;
	float coef;
	PolyList p,rear;//指向最后一个结点 
	L = (PolyList) malloc (sizeof (LNode));
	L->next = NULL;    // 先建立一个带头结点的单链表
	rear=L;
	printf("输入0 0代表结束:\n");
	for ( ; 1 ; ) 
	{
		scanf("%f%d",&coef,&exp);
		if(fabs(coef)<0.00001)//浮点数的相等的判断一般不用双等号,当两个浮点数的差的绝对值足够小时,即认为两个浮点数相等 
			break; 
    	p = (PolyList) malloc (sizeof (LNode));
 		p->coef=coef;
 		p->exp=exp;
 		p->next=NULL;
    	rear->next=p;
    	rear=p;
	}
}
void DestroyList(PolyList &L) 
{
	PolyList p;
    while (L) 
	{
        p=L;    
		L=L->next;
        free(p);
    }
} 

int main()
{
	PolyList head1,head2;
	printf("请输入多项式(A)各项的系数和指数,");
	CreatePoly(head1);
	printf("请输入多项式(B)各项的系数和指数,");
	CreatePoly(head2);
	head1=addpoly(head1, head2);
	PrintPoly(head1);
	DestroyList(head1);  //释放空间 
    return 0;
}

 

本文链接http://element-ui.cn/article/show-155875.aspx