使用链表进行数据的存储,包括指数和系数到两者都为0时结束;
将add()函数设置为友元函数方便调用;
#include<iostream>
using namespace std;
struct node
{
int coef;
int exp;
node* next;
};
class linklist
{
public:
linklist();
friend void add(linklist &a,linklist &b);
void print();
private:
node* first;
};
linklist::linklist()
{
node* p = NULL, * s = NULL;
first = new node;
p = first;
int coef, exp;
while (1)
{
cout << "请输入系数和指数:";
cin >> coef >> exp;
if (coef == 0 && exp == 0)
break;
s = new node;
s->coef = coef;
s->exp = exp;
p->next = s;
p = s;
}
p->next = NULL;
}
void linklist::print()
{
node* p = first->next;
if (p != NULL)
{
if (p->exp != 0)
cout << p->coef << "x^" << p->exp;
else
cout << p->coef;
p = p->next;
}
while (p != NULL)
{
if (p->coef > 0)
cout << " + " << p->coef << "x^" << p->exp;
else
cout << p->coef << "x^" << p->exp;
p = p->next;
}
cout << endl;
}
void add(linklist& a, linklist& b)
{
node* pre, * p, * qre, * q, * v;
pre = a.first; p = pre->next;
qre = b.first; q = qre->next;
while (p != NULL && q != NULL)
{
if (p->exp < q->exp)
{
pre = p;
p = p->next;
}
else if (p->exp > q->exp)
{
v = q->next;
pre->next = q;
q->next = p;
q = v;
}
else
{
p->coef = p->coef + q->coef;
if (p->coef == 0)
{
pre->next = p->next;
delete p;
p = pre->next;
}
else {
pre = p;
p = p->next;
}
qre->next = q->next;
delete q;
q = qre->next;
}
}
if (q != NULL)pre->next = q;
delete b.first;
}
int main()
{
linklist a, b;
add(a, b);
a.print();
return 0;
}
运行结果如下