首页 > 代码库 > 多项式相加(顺序表)

多项式相加(顺序表)

#include <iostream.h>
typedef struct 
{
    int coef;
    int index;
}datatype ;
typedef struct
{
    datatype *elem;
    int length;
}SeqList;
void BuildPoly(SeqList &s)
{
    s.elem=new datatype[10];
    s.length=0;int i=1;
    cin>>s.elem->coef>>s.elem->index;
    while(s.elem[i-1].coef!=-1&&s.elem[i-1].index!=-1)
    {s.length=i;
    cin>>s.elem[i].coef>>s.elem[i].index;i++;}
}
void AddPoly(SeqList s1,SeqList s2,SeqList &s3)
{
   s3.elem=new datatype[10];
   s3.length=0;
   datatype *p1=s1.elem,*p2=s2.elem,*p3=s3.elem;
   while(p1-s1.elem<s1.length&&p2-s2.elem<s2.length)
   {
       if(p1->index<p2->index)
       {p3->coef=p1->coef;p3->index=p1->index;
         p1++;p3++;s3.length++;
       }
       else if(p1->index>p2->index)
       {p3->coef=p2->coef;p3->index=p2->index;
         p2++;p3++;s3.length++;}
       else if(p1->index==p2->index)
       {
           if(p1->coef+p2->coef!=0)
           {
               p3->coef=p1->coef+p2->coef;
               p3->index=p1->index;
               p3++;s3.length++;
           }
           p1++;p2++;
       }
   }
   while(p1-s1.elem<s1.length)
   {
      p3->coef=p1->coef;p3->index=p1->index;
         p1++;p3++;s3.length++;
   }
     while(p2-s2.elem<s2.length)
   {
      p3->coef=p2->coef;p3->index=p2->index;
         p2++;p3++;s3.length++;
   }
}

void DispList(SeqList s)
{
    for(int i=0;i<s.length;i++)
    {        cout<<s.elem[i].coef<<\t<<s.elem[i].index<<\t;}
cout<<endl;

}

void main()
{
   SeqList s1,s2,s3;
   BuildPoly(s1);
   BuildPoly(s2);
   AddPoly(s1,s2,s3);
   DispList(s3);
}

 

多项式相加(顺序表)