多项式相加(链表)
#include<iostream>
using namespace std;
class poly{
public:
int coef;
int expon;
poly *next;
};
poly*input(); //输入函数
poly *polyadd(poly *p1, poly *p2); //相加函数
poly *attach(poly*rear, int coef, int expon); //链接函数
int compare(int a, int b); //大小比较函数
int main()
{
cout << "请输入多项式p1:" << endl;
poly*p1 = input();
cout << "请输入多项式p2:" << endl;
poly*p2 = input();
poly*p3 = polyadd(p1, p2);
cout << "p1+p2后为:" << endl;
while (p3){
cout << p3->coef << ' ' << p3->expon << endl; //输出结果
p3 = p3->next;
}
return 0;
}
poly*input()
{
poly*p = new poly;
poly*head = p, *p1 = p;
cout << "请输入系数和指数,以系数为0表示结束;" << endl;
cin >> p->coef >> p->expon;
if (p->coef == 0){
head->next =NULL;
return head;
}
while (p->coef){
p1 = p;
p = new poly;
cin >> p->coef >> p->expon;
p1->next = p;
}
delete p;
p1->next = NULL;
return head;
}
poly *polyadd(poly *p1, poly *p2)
{
int sum;
poly*p = new poly;
poly*head = p,*rear = p;
while (p1&&p2){
switch (compare(p1->expon, p2->expon)){ //每次均要比较p1和p2的指数
case 1:
rear=attach(rear, p1->coef, p1->expon); //每次循环都更换未结点
p1 = p1->next; //下移动一个结点
break;
case -1:
rear=attach(rear, p2->coef, p2->expon);
p2 = p2->next; //下移动一个结点
break;
case 0:
sum = p1->coef + p2->coef;
if (sum) //若果系数不为0
rear=attach(rear, sum, p1->expon);
p1 = p1->next;
p2 = p2->next;
break;
}
}
while (p1){ //上面跳出来的结果要么p1为空,要么p2为空
rear=attach(rear, p1->coef, p1->expon);
p1 = p1->next;
}
while (p2){
rear=attach(rear, p2->coef, p2->expon);
p2 = p2->next;
}
rear->next = NULL; //未结点的next指针指向空
poly*temp = head;
head = head->next;
delete temp; //删除空的头结点
return head; //返回头结点
}
poly *attach(poly *rear,int sum, int expon)
{
poly*p = new poly;
p->coef = sum;
p->expon = expon;
rear->next = p; //将结果连接在一起
return p;
}
int compare(int a, int b)
{
if (a > b)
return 1;
else if (a == b)
return 0;
return -1;
}