02-线性结构2 一元多项式的乘法与加法运算(20 分)
设计函数分别求两个一元多项式的乘积与和。
1 #include<iostream> 2 3 using namespace std; 4 struct PolyNode{ 5 int xishu; 6 int cishu; 7 PolyNode* Next; 8 }; 9 using list=PolyNode*; 10 list Read(){ 11 int n; 12 cin>>n; 13 list s=(list)malloc(sizeof(PolyNode)); 14 list m=s; 15 s->Next=NULL; 16 while(n--) 17 { 18 int i,j; 19 cin>>i>>j; 20 list t=(list)malloc(sizeof(PolyNode)); 21 t->xishu=i; t->cishu=j; 22 m->Next=t; 23 m=m->Next; 24 } 25 m->Next=NULL; 26 list temp=s; 27 s=s->Next; 28 free(temp); 29 return s; 30 } 31 void attach(int i,int j,list* l){ 32 list m=(list)malloc(sizeof(PolyNode)); 33 m->xishu=i; m->cishu=j; 34 m->Next=NULL; 35 (*l)->Next=m; 36 (*l)=m; 37 } 38 list add(list l1,list l2) 39 { 40 list s=(list)malloc(sizeof(PolyNode)); 41 list m=s; 42 s->Next=NULL; 43 while(l1&&l2) 44 { 45 if(l1->cishu==l2->cishu){ 46 if(l1->xishu+l2->xishu) 47 attach(l1->xishu+l2->xishu,l1->cishu,&m); 48 l1=l1->Next; l2=l2->Next; 49 }else if(l1->cishu<l2->cishu){ 50 attach(l2->xishu,l2->cishu,&m); 51 l2=l2->Next; 52 }else if(l1->cishu>l2->cishu){ 53 attach(l1->xishu,l1->cishu,&m); 54 l1=l1->Next; 55 } 56 } 57 while(l1){ 58 attach(l1->xishu,l1->cishu,&m); 59 l1=l1->Next; 60 } 61 while(l2){ 62 attach(l2->xishu,l2->cishu,&m); 63 l2=l2->Next; 64 } 65 list temp=s; 66 s=s->Next; 67 free(temp); 68 return s; 69 } 70 list multiply(list l1,list l2) 71 { 72 list s,m,p,q; 73 p=l1; q=l2; 74 if(!p||!q) 75 return NULL; 76 s=(list)malloc(sizeof(PolyNode)); 77 m=s; 78 s->Next=NULL; 79 while(q){ 80 attach(p->xishu*q->xishu,p->cishu+q->cishu,&m); 81 q=q->Next; 82 } 83 p=p->Next; 84 while(p){ 85 q=l2;list rear=s; 86 while(q){ 87 int sum=p->cishu+q->cishu; 88 int mul=p->xishu*q->xishu; 89 while(rear->Next&&(rear->Next)->cishu>sum) 90 rear=rear->Next; 91 if(rear->Next&&(rear->Next)->cishu==sum){ 92 if((rear->Next)->xishu+mul) 93 (rear->Next)->xishu+=mul; 94 else 95 {list t=rear->Next; 96 rear->Next=t->Next; 97 free(t); 98 } 99 } 100 else { 101 list e=(list)malloc(sizeof(PolyNode)); 102 e->xishu=mul; e->cishu=sum; 103 e->Next=rear->Next; rear->Next=e; 104 } 105 q=q->Next; 106 } 107 p=p->Next; 108 } 109 list temp=s; 110 s=s->Next; 111 free(temp); 112 return s; 113 } 114 void print(list li) 115 { 116 if(!li) 117 cout<<0<<" "<<0; 118 int tag=1; 119 while(li){ 120 if(tag){ 121 cout<<li->xishu<<" "<<li->cishu; 122 tag=0; li=li->Next; 123 } 124 else{ 125 cout<<" "<<li->xishu<<" "<<li->cishu; 126 li=li->Next; 127 } 128 129 } 130 cout<<endl; 131 } 132 int main() 133 { 134 list l1=Read(); 135 list l2=Read(); 136 list l3=multiply(l1,l2); 137 list l4=add(l1,l2); 138 print(l3); 139 print(l4); 140 return 0; 141 }