#include <iostream>
using namespace std;
template <typename T>
struct LNode
{
T data;
LNode<T>* next;
LNode() : next(NULL) {}
LNode(T e, LNode<T>* n = NULL) :data(e), next(n) {}
};
template<typename T>
class List {
protected:
int _size;
LNode<T>* header;
public:
List() : _size(0), header(NULL) {}
int size() const { return _size; }
bool empty() const { return !_size; }
LNode<T>* head() const { return header->next; }
~List()
{
while (header)
{
LNode<T>* p = header;
header = header->next;
delete p;
}
}
void insert(T const& e)
{
_size++;
LNode<T>* p = new LNode<T>(e, header->next);
header->next = p;
}
};
struct Mono
{
double coef;
int exp;
};
class poly : public List<Mono>
{
public:
void merge_poly(poly& La, poly& Lb)
{
init();
int tmp = 0;
LNode<Mono>* pa, * pb, * pc;
pa = La.head();
pb = Lb.head();
pc = header;
while (pa && pb)
{
if (pa->data.exp == pb->data.exp)
{
pa->data.coef += pb->data.coef;
if (pa->data.coef != 0)
{
pc->next = pa;
pc = pa;
tmp++;
}
pa = pa->next;
pb = pb->next;
tmp -= 2;
}
else if (pa->data.exp < pb->data.exp)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
else
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
_size = La.size() + Lb.size() + tmp;
La.init();
Lb.init();
}
};
void creat_poly(poly& L)
{
double c; int index;
while (cin >> c >> index)
{
if (c == 0 && index == 0) {
break;
}
L.insert({ c,index });
}
}
void print_poly(poly& L)
{
cout << "共有" << L.size() << "项:";
for (LNode<Mono>* p = L.head(); p; p = p->next)
{
if (p->data.coef != 0)
{
if (p != L.head())
cout << ((p->data.coef > 0) ? '+' : '-');
if (!p->data.exp)
cout << abs(p->data.coef);
else if (p->data.exp == 1)
cout << abs(p->data.coef) << 'x';
else
cout << abs(p->data.coef) << "x^" << p->data.exp;
}
}
cout << endl;
}
int main()
{
poly La, Lb, Lc;
creat_poly(La);
creat_poly(Lb);
cout << "一元多项式La为:" << endl;
print_poly(La);
cout << "一元多项式Lb为:" << endl;
print_poly(Lb);
Lc.merge_poly(La, Lb);
cout << "一元多项式La和Lb相加后的一元多项式Lc为:" << endl;
print_poly(Lc);
return 0;
}
该代码是一个简单的多项式相加的程序,使用链表实现。将#define NULL 0
和 #define ERROR 0
移除,并进行了一些修正以使代码符合C++标准。修复了对负数系数的输出错误,改为输出绝对值并添加正负号。
内容由零声教学AI助手提供,问题来源于学员提问