目录
1.多项式的创建和打印
#include <iostream>
using namespace std;
typedef struct PolyNode {
int coef; //系数
int expn; //指数
PolyNode *next;
} *LIST, *Node;
void CreatPolyList(LIST &L, int n)
{
Node node, last; //与单链表的创建同理
L = last = new PolyNode;
cout << "输入成对的系数和指数: " << endl;
for (int i = 0; i < n; i++) {
node = new PolyNode;
last->next = node;
cin >> node->coef >> node->expn;
last = node;
}
last->next = NULL;
}
void PrintPolyList(LIST &L)
{
Node p = L->next; //与单链表的输出同理
cout << p->coef << "X^" << p->expn;
for (p = p->next; p; p = p->next) {
cout << "+" << p->coef << "X^" << p->expn;
}
cout << endl;
}
2.多项式的相加相乘
LIST Plus(LIST &L1, LIST &L2)
{ //多项式相加类似于单链表的归并
Node node, last, p1 = L1->next, p2 = L2->next;
LIST L = last = new PolyNode;
while (p1 && p2) {
if (p1->expn > p2->expn) {
last->next = p1;
last = p1;
p1 = p1->next;
} else if (p1->expn < p2->expn) {
last->next = p2;
last = p2;
p2 = p2->next;
} else {
Node node = new PolyNode;
node->coef = p1->coef + p2->coef;
node->expn = p1->expn;
last->next = node;
last = node;
p1 = p1->next; //由于此条件下相加了两个同指数项!
p2 = p2->next; //所以两个表的待插入结点都需要更新
}
}
last->next = p1 ? p1 : p2; //复制表中剩余结点
return L;
}
LIST Multiply(LIST &L1, LIST &L2)
{
Node p, p1, p2, last;
LIST L = last = new PolyNode;
p1 = L1->next;
while (p1 != NULL) {
p2 = L2->next;
while (p2 != NULL) {
p = new PolyNode;
p->coef = (p1->coef) * (p2->coef);
p->expn = (p1->expn) + (p2->expn);
last->next = p;
last = p;
p2 = p2->next;
}
p1 = p1->next;
}
last->next = NULL;
return L;
}
3.多项式示例
int main()
{
LIST L1, L2, L3, L4;
CreatPolyList(L1, 2);
cout << "创建的多项式1";
PrintPolyList(L1);
CreatPolyList(L2, 2);
cout << "创建的多项式2";
PrintPolyList(L2);
cout << "多项式相加后为: ";
L3 = Plus(L1, L2);
PrintPolyList(L3);
cout << "多项式相乘后为: ";
L4 = Multiply(L1, L2);
PrintPolyList(L4);
return 0;
}