#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 CreatList()
{
List L=new struct Node;
L->Next = NULL;
List rear = L;
int N;
double coef;
int expon;
cin >> N;
cin.get();
while (N--)
{
cin >> expon;
cin.get();
cin >> coef;
cin.get();
Attach(expon, coef,&rear);
}
List tmp = L;
L = L->Next;
delete tmp;
return L;
}
int Compare(int a, int b)
{
if (a > b)return 1;
if (a < b)return -1;
if (a == b)return 0;
}
List Add(List L1, List L2)
{
List p1, p2;
List L = new struct Node;
L->Next = NULL;
List rear = L;
p1 = L1, p2 = L2;
while (p1&&p2)
{
switch (Compare(p1->expon, p2->expon))
{
case 1:
Attach(p1->expon, p1->coef, &rear);
p1 = p1->Next;
break;
case -1:
Attach(p2->expon, p2->coef, &rear);
p2 = p2->Next;
break;
case 0:
if (p1->coef + p2->coef == 0);
else
Attach(p1->expon, p1->coef + p2->coef, &rear);
p1 = p1->Next;
p2 = p2->Next;
break;
}
}
while (p1)
{
Attach(p1->expon, p1->coef, &rear);
p1 = p1->Next;
}
while (p2)
{
Attach(p2->expon, p2->coef, &rear);
p2 = p2->Next;
}
List tmp = L;
L = L->Next;
delete tmp;
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 = CreatList();
List L2 = CreatList();
List L = Add(L1, L2);
Print(L);
return 0;
}
精度设置:头文件include<iomanip>,小数点后一位设置setiosflags(ios::fixed)<<setprecision(1)
1002. A+B for Polynomials (25)
最新推荐文章于 2022-03-31 12:08:15 发布