一元多项式的加法运算

include<stdio.h>

include<stdlib.h>

//链表实现
struct node{
int cofe;
int expn;
struct node next;
};
typedef struct node
Node;
Node Creatlist()//带头结点
{
Node head;
head=(Node)malloc(sizeof(struct node));
head->next=NULL;
return head;
}
void AddNode(Node rear,int cofe,int expn)
{
Node Newp;
Newp=(Node)malloc(sizeof(struct node));
Newp->cofe=cofe;
Newp->expn=expn;
Newp->next=NULL;
rear->next=Newp;
rear=Newp;
}
Node Findrear(Node head)
{
while(head->next)
{
head=head->next;
}
return head;
}
void print(Node head)
{
head=head->next;
while(head)
{
printf("%d %d ",head->cofe,head->expn);
head=head->next;
}
}
Node Mix(Node head1,Node head2)
{
Node List,rear,Newp;
List=(Node)malloc(sizeof(struct node));
List->next=NULL;
head1=head1->next;
head2=head2->next;
while(head1&&head2)
{
Newp=(Node)malloc(sizeof(struct node));

	if(head1->expn>head2->expn)
	{
		Newp->cofe=head1->cofe;
        Newp->expn=head1->expn;
        head1=head1->next;
	}
    else if(head1->expn<head2->expn)
	{
		Newp->cofe=head2->cofe;
        Newp->expn=head2->expn;
        head2=head2->next;
	}
    else
    {
        Newp->cofe=head1->cofe+head2->cofe;
         Newp->expn=head1->expn;
        head1=head1->next;
        head2=head2->next;
    }
    if(Newp->cofe){
    Newp->next=NULL; 
    rear=Findrear(List);
    rear->next=Newp;
    rear=Newp;
    }
    else free(Newp);//系数和为0;
}
 while(head1)
 {
 	Newp=(Node)malloc(sizeof(struct node));
 	Newp->cofe=head1->cofe;
    Newp->expn=head1->expn;
    Newp->next=NULL; 
   
 	rear=Findrear(List);
    rear->next=Newp;
    rear=Newp;
    
     head1=head1->next;
  } 
  while(head2)
 {
 	Newp=(Node)malloc(sizeof(struct node));
 	Newp->cofe=head2->cofe;
    Newp->expn=head2->expn;
    Newp->next=NULL; 
   
 	rear=Findrear(List);
    rear->next=Newp;
    rear=Newp;
    
     head2=head2->next;
  } 
 
return List;

}
int main()
{
Node head1,rear1,head2,rear2,List;

head1=Creatlist();
rear1=Findrear(head1);

head2=Creatlist();
rear2=Findrear(head2);
int n,m,i,cofe,expn;//n,m分别是项的个数 

scanf("%d",&n);
for(i=0;i<n;i++)
{
	scanf("%d %d",&cofe,&expn);
	rear1=Findrear(head1);
	AddNode(rear1,cofe,expn);
 } 
 getchar();
 scanf("%d",&m);
for(i=0;i<m;i++)
{
	scanf("%d %d",&cofe,&expn);
	rear2=Findrear(head2);
	AddNode(rear2,cofe,expn);
 } 
 List=Mix(head1,head2);
print(List);

}

posted @ 2021-08-17 14:22  日月既往、不复可追。  阅读(41)  评论(0编辑  收藏  举报
Fork me on GitHub /*音乐*/ 1 2 3
4