1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| ```c++ #include<bits/stdc++.h> #include<string> #include<cctype> using namespace std;
struct PolyNode{ int coef; int expon; struct PolyNode * link; }; typedef struct PolyNode *Poly; Poly P1, P2; int Compare(int a,int b) { if(a>b) return 1; else if(a==b) return 0; else return -1; } void Attach(int c,int e,Poly * pRear) { Poly P; P=(Poly)malloc(sizeof(struct PolyNode)); P->coef=c; P->expon=e; P->link=NULL; (*pRear)->link=P; *pRear=P; } Poly PolyAdd(Poly P1, Poly P2) { Poly front, rear, temp; int sum; rear = (Poly)malloc(sizeof(struct PolyNode)); front = rear; while (P1&&P2) { switch(Compare(P1->expon,P2->expon)){ case 1: Attach(P1->coef,P1->expon,&rear); P1=P1->link; break; case -1: Attach(P2->coef,P2->expon,&rear); P2=P2->link; break; case 0: sum=P1->coef+P2->coef; if(sum) Attach(sum,P1->expon,&rear); P1=P1->link; P2=P2->link; break; } } for(;P1;P1=P1->link) Attach(P1->coef,P1->expon,&rear); for(;P2;P2=P2->link) Attach(P2->coef,P2->expon,&rear); rear->link=NULL; temp=front; front=front->link; free(temp); return front; }
Poly ReadPoly() { int N,c,e; Poly Rear,P,t; cin>>N; P=(Poly)malloc(sizeof(struct PolyNode)); P->link=NULL; Rear=P; while(N--){ cin>>c>>e; Attach(c,e,&Rear); } t=P;P=P->link;free(t); return P; } void PrintPoly(Poly p) { int flag=0; if(!p) cout<<"0"<<endl; while(p){ if(!flag) flag=1; else cout<<" "; cout<<p->coef<<" "<<p->expon<<" "; p=p->link; } } int main() { Poly P1,P2,PS; P1=ReadPoly(); P2=ReadPoly(); PS=PolyAdd(P1,P2); PrintPoly(PS); return 0; }
|