#include<iostream>
#include<iomanip>
using namespace std;
typedef struct Node * List;
struct Node {
int expon;
double coef;
List Next;
};
void Attach(int expon, double coef, List * Rear)
{
List tmp = new struct Node;
tmp->coef = coef;
tmp->expon = expon;
tmp->Next = NULL;
(*Rear)->Next = tmp;
*Rear = tmp;
}
List ReadList()
{
List L = new struct Node;
L->Next = NULL;
List rear = L;
int N;
cin >> N;
double coef;
int expon;
while (N--)
{
cin >> expon;
cin >> coef;
Attach(expon, coef, &rear);
}
L = L->Next;
return L;
}
void Insert(List L, int expon, double coef) //L头结点是空的,这种用p->Next很方便
{
List p = L;
while (p->Next&&p->Next->expon > expon)
p = p->Next;
if (p->Next&&p->Next->expon == expon)
{
if (p->Next->coef + coef == 0)
{
List tmp = p->Next;
p->Next = tmp->Next;
delete tmp;
}
else
p->Next->coef += coef;
}
else //到了最后一个节点后的空节点或者加在两个节点中间
{
List tmp = new struct Node;
tmp->coef = coef;
tmp->expon = expon;
tmp->Next = p->Next;
p->Next = tmp;
}
}
List Mult(List L1, List L2)
{
if (!L1 || !L2)return NULL;
List p1 = L1, p2 = L2;
List L = new struct Node;
L->Next = NULL;
List rear = L;
double coef;
int expon;
while (p2)
{
expon = p1->expon + p2->expon;
coef = p1->coef*p2->coef;
Attach(expon, coef, &rear);
p2 = p2->Next;
}
p1 = L1->Next;
p2 = L2;
while (p1)
{
p2 = L2;
while (p2)
{
expon = p1->expon + p2->expon;
coef = p1->coef*p2->coef;
Insert(L, expon, coef);
p2 = p2->Next;
}
p1 = p1->Next;
}
L = L->Next;
return L;
}
void Print(List L)
{
List p = L;
int count = 0;
while (p)
{
count++;
p = p->Next;
}
cout << count;
p = L;
while (p)
{
cout <<" "<< p->expon << " " << setiosflags(ios::fixed) << setprecision(1) << p->coef;
p = p->Next;
}
}
int main()
{
List L1 = ReadList();
List L2 = ReadList();
List L = Mult(L1, L2);
Print(L);
return 0;
}
/*2 1 2.4 0 3.2 2 2 1.5 1 0.5*/
Insert函数中每次插进一个新元素都要从头开始扫描
陈越老师讲的那个方法很巧妙,每次进来的指数肯定在Rear或者Rear后面,前面的就不用扫描,直接插在后面就可以