1. 程式人生 > 其它 >一元多項式的加法運算

一元多項式的加法運算

#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;
        }
        Newp->next=NULL; 
        rear=Findrear(List);
        rear->next=Newp;
        rear=Newp;
    }
     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);
    
}