创建多项式

C语言数据结构作业,创建多项式,实现2条多项式的相加

#include
#include
typedef struct Node{
	float xnum;
	int znum;
	struct  Node *next;
}Node;

//创建多项式
Node *InsertNode(Node *head)
{
	void printNode(Node *head);
	Node *p1=NULL,*tem,*p2;
	p1=(Node*)malloc(sizeof(Node));
	head=p1;
	head->next=NULL;
	p1->znum=-1;
	while(1)
	{
		p1=head;
		p2=head;
		tem=(Node*)malloc(sizeof(Node));
		tem->next=NULL;
		if(scanf("%f%d",&tem->xnum,&tem->znum)==EOF)
			break;
		if(tem->xnum==0)
			continue;
		while(tem->znum>p1->znum){
		p2=p1;
		p1=p1->next;
		if(p1==NULL)
			break;
		}
		if(p1==NULL)
			p2->next=tem;
		else if(tem->znum==p1->znum)
		{
			p1->xnum+=tem->xnum;
		}
		else
		{
			tem->next=p1;
			p2->next=tem;
		}
	}
	return head->next;
}

//多项式相加
void Radd(Node *head1,Node *head2){
	Node *phead=NULL,*p=NULL,*tem;
	void printNode(Node *head);
	p= (Node*)malloc(sizeof(Node));
	phead=p;
	while (head1!= NULL&&head2!=NULL){
			tem = (Node*)malloc(sizeof(Node));
			tem->next=NULL;
			if (head1->znum < head2->znum)
			{																													
				tem->xnum= head1->xnum;
				tem->znum=head1->znum;
				head1 = head1->next;
			}
			else if (head1->znum>head2->znum){
				tem->xnum= head2->xnum;
				tem->znum=head2->znum;
				head2 = head2->next;
			}
			else if (head1->znum == head2->znum)
			{
				tem->xnum = head1->xnum + head2->xnum;
				if(tem->xnum==0)
					continue;
				tem->znum = head1->znum;
				head1 = head1->next;
				head2 = head2->next;
			}
			p->next=tem;
			p=p->next;
	}
	if(head1==NULL)
		p->next=head2;
	else
		p->next=head1;
	printNode(phead->next);
}

//多项式输出
void printNode(Node *head)
{
	while(head!=NULL){
		printf("%fx^%d",head->xnum,head->znum);
		if(head->next!=NULL)
			printf("+");
		head=head->next;
	}
}

//主函数
int main(){
	Node *head1=NULL,*head2=NULL;
	printf("输入第一个多项式:\n");
	head1=InsertNode(head1);
	printf("输入第二个多项式:\n");
	head2=InsertNode(head2);
	Radd(head1,head2);
	return 0;
}

 

你可能感兴趣的:(c)