PAT 1009 Product of Polynomials (25 分)
多项式链表的乘积
用链表L1的每一个节点和链表L2的每一个节点相乘之后进行加和,生成新的结果链表
具体代码
#include<iostream>
#include<malloc.h>
#include<iomanip>
using namespace std;
typedef struct node* Node;
struct node
{
int exp;
float cof;
Node next;
};
typedef Node List;
List insert(List p, Node tmp)
{
Node p1 = p;
while ((p1->next)&&(p1->next->exp>tmp->exp))
{
p1 = p1->next;
}
if (p1->next == NULL)
{
p1->next = tmp;
return p;
}
else
{
if (p1->next->exp == tmp->exp)
{
if (p1->next->cof + tmp->cof == 0)
{
Node t = p1->next;
p1->next = t->next;
free(t);
free(tmp);
return p;
}
else
{
p1->next->cof = p1->next->cof + tmp->cof;
free(tmp);
return p;
}
}
else
{
tmp->next = p1->next;
p1->next = tmp;
return p;
}
}
}
List create()
{
int n;
cin >> n;//表明当前的节点数目
List p = (List)malloc(sizeof(struct node));
p->next = NULL;
for (int i = 1; i <= n; i++)
{
Node tmp = (Node)malloc(sizeof(struct node));
cin >> tmp->exp >> tmp->cof;
tmp->next = NULL;
p = insert(p, tmp);
}
return p;
}
List multiply(List L1, List L2)
{
Node p1, p2;
List L3 = (List)malloc(sizeof(struct node));
L3->next = NULL;
for (p1 = L1->next; p1; p1 = p1->next)
{
for (p2 = L2->next; p2; p2 = p2->next)
{
Node t = (Node)malloc(sizeof(struct node));
t->exp = p1->exp + p2->exp;
t->cof = p1->cof * p2->cof;
t->next = NULL;
insert(L3, t);
}
}
return L3;
}
void print(List L)
{
int count = 0;
Node p1 = L->next;
while (p1)
{
count++;
p1 = p1->next;
}
Node p = L->next;
cout.setf(ios::fixed);
cout << count;
while (p)
{
cout << " " << p->exp << " " << setprecision(1) << p->cof;
p = p->next;
}
}
int main()
{
List L1 = create();
//print(L1);
List L2 = create();
//print(L2);
print(multiply(L1, L2));
return 0;
}