#include <stdio.h>#include<stdlib.h>typedefstructpolynode*polynomial;structpolynode{intCoef; intExpon; polynomial link;};intCompare (intE1,intE2);voidAttachintCinte,polynomial*reat); Polynomial Readpoly (); Polynomial add (polynomial p1,polynomial P2);voidprintpoly (polynomial P);intMain () {polynomial p1,p2,pp; P1=Readpoly (); P2=Readpoly (); PP=Add (P1,P2); Printpoly (PP); return 0;}intCompare (intE1,intE2) { if(E1>E2)return 1; Else if(E1<E2)return-1; Else return 0;}voidAttachintCinte,polynomial*reat) {polynomial P; P= (polynomial)malloc(sizeof(structPolynode)); P->coef=C; P->expon=e; P->link=NULL; (*reat)->link=Q; *reat=P;} Polynomial Readpoly () {intn,c,e; Polynomial p,rear,t; P= (polynomial)malloc(sizeof(structPolynode)); P->link=NULL; Rear=Q; scanf ("%d",&N); while(n--) {scanf ("%d%d",&c,&e); Attach (C,e,&rear); } t=p; p=p->link; Free(t); returnP;} Polynomial add (polynomial p1,polynomial P2) {intsum; Polynomial front,rear,temp; Front= (polynomial)malloc(sizeof(structPolynode)); Rear=Front; 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; 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); returnFront;}voidprintpoly (polynomial P) {intflag=0; if(!P) {printf ("0 0\n"); return; } while(P) {if(!flag) Flag=1; Elseprintf (" "); printf ("%d%d",p->coef,p->expon); P=p->link; }}
Pay special attention to the Attach function:
void Attach (int c,int e,polynomial*reat) { polynomial P; P= (polynomial)malloc(sizeof(struct polynode)); P->coef=C; P->expon=e; P->link=NULL; (*reat)->link=P; *reat=P;}
One of the parameters polynomial*reat, the address of the address used, if it is only used polynomial type, then the equivalent of just passing in an address value, the function call will release the address of the parameter, so the tail of the list will not change, so need to use polynomial* The Reat type.
List of linked lists for polynomial addition