## C++多项式的乘法

``````/*
*改编：苏格扯底
*
*
*
*
*
*
*/

#include<iostream>
using namespace std;
typedef struct pnode {

int coef;
int exp;
pnode* next;
}pnode;
class poly {

private:
public:
poly() {
void create(int n);
void print();
int comp(int a, int b);
//在ha中加项x，
void timespoly(poly& hc, poly ha, poly hb);

};
void poly::create(int n) {

pnode* rear = head, * s;
for (int i = 0; i < n; i++) {

s = new pnode;
cin >> s->coef >> s->exp;
rear->next = s;
rear = s;
}
rear->next = NULL;
}
void poly::print() {

while (p) {

cout << p->coef << ' ' << p->exp << ',';
p = p->next;
}
cout << endl;
}
int poly::comp(int a, int b) {

if (a > b)return -1;
else if (a == b)return 0;
else return 1;
}

//把hb多项式加到ha多项式上去
void poly::addpoly(poly& ha, poly hb) {

while (pa && pb)
switch (comp(pa->exp, pb->exp)) {

case -1:q = pa; pa = pa->next; break;
case 1:r = new pnode;
r->coef = pb->coef;
r->exp = pb->exp;
r->next = pa;
q->next = r;
q = r;
pb = pb->next;
break;
case 0:pa->coef += pb->coef;
if (pa->coef == 0) {

q->next = pa->next;
delete pa;
pa = q;
}
else q = pa;
pa = pa->next;
pb = pb->next;
break;
}
while (pb) {

r = new pnode;
r->coef = pb->coef;
r->exp = pb->exp;
r->next = NULL;
q->next = r;
q - r;
pb = pb->next;
}
}

{

if (pa == NULL)
{

r = new pnode;
r->coef = x->coef;
r->exp = x->exp;
r->next = pa;
q->next = r;
q = r;
return;
}
while (pa)
switch (comp(pa->exp, x->exp)) {

case -1: q = pa; pa = pa->next;
if (pa == NULL)
{

r = new pnode;
r->coef = x->coef;
r->exp = x->exp;
r->next = pa;
q->next = r;
q = r;
return;
}break;
case 1:r = new pnode;
r->coef = x->coef;
r->exp = x->exp;
r->next = pa;
q->next = r;
q = r;
break;
case 0:pa->coef += x->coef;
if (pa->coef == 0) {

q->next = pa->next;
delete pa;
pa = q;
}//系数为0的话就删除该节点
else q = pa;
pa = pa->next;
break;

}

}

//把ha，hb相乘得到hc
void poly::timespoly(poly& hc, poly ha, poly hb)
{

pnode* r;
while (pa) {

while (pb)
{

r = new pnode;
r->coef = pa->coef * pb->coef;//系数相乘
r->exp = pa->exp + pb->exp;//指数相加
pb = pb->next;
}
pa = pa->next;

}
}

int main() {

poly ha, hb,hc;
ha.create(2);
hb.create(3);
ha.print();
hb.print();
ha.timespoly(hc,ha,hb);
hc.print();

return 0;
}

``````