这一篇实现了对x多项式的乘法,计算过程分为两步:
1.先对两个多项式进行乘法合并
2.对合并后的多项式进行整合
需要特别说明一下:这里的分步计算和整合是借鉴了一篇csdn优秀作者的文章的,但是现在因为距离实现这段代码也过去了很长一段时间,暂时找不到那篇文章了,如果侵权了可以联系我删除。
#include <iostream>
#include <malloc.h>
using namespace std;
typedef int Elementtype;
struct polynomial {
Elementtype coenum;
Elementtype index;
polynomial *next;
};
typedef polynomial *POLY;
//借用Mul函数对乘法运算过的多项式进行整合
POLY Mul(POLY P3) {
polynomial *p, *q, *set;
set = P3;
p = P3->next;
while (set->next != NULL) {
set = set->next;
while (p->next != NULL) {
q = p;
p = p->next;
if (set->index == p->index) {
set->coenum += p->coenum;
q->next = p->next;
q = p;
p = p->next;
delete q;
}
}
p = set->next;
}
return P3;
}
POLY Multiply(POLY P1, POLY P2) {
POLY P3;
P3 = (POLY)malloc(sizeof(polynomial));
polynomial *s, *r = P3, *p = P1->next, *q;
while (p != NULL) {
q = P2->next;
while (q != NULL) {
s = (polynomial *)malloc(sizeof(polynomial));
s->coenum = p->coenum * q->coenum;
s->index = p->index + q->index;
r->next = s;
r = s;
q = q->next;
}
p = p->next;
}
return Mul(P3);
}
int main() {
POLY P1, P2;
P1 = (POLY)malloc(sizeof(polynomial));
P2 = (POLY)malloc(sizeof(polynomial));
polynomial *s1, *r1 = P1, *print1 = P1;
polynomial *s2, *r2 = P2, *print2 = P2;
Elementtype c1[5] = {1, 2, 3, 4, 5};
Elementtype b1[5] = {1, 3, 6, 3, 4};
Elementtype c2[5] = {1, 2, 3, 4, 5};
Elementtype b2[5] = {2, 4, 7, 3, 5};
for (int i = 0; i < 5; i++) {
s1 = (polynomial *)malloc(sizeof(polynomial));
s1->coenum = b1[i];
s1->index = c1[i];
r1->next = s1;
r1 = s1;
}
r1->next = NULL;
for (int j = 0; j < 5; j++) {
s2 = (polynomial *)malloc(sizeof(polynomial));
s2->coenum = b2[j];
s2->index = c2[j];
r2->next = s2;
r2 = s2;
}
r2->next = NULL;
cout << "The First Polynomial is :" << endl;
while (print1->next != NULL) {
cout << print1->next->coenum << "X" << "^" << print1->next->index ;
if (print1->next->next != NULL)
cout << "+";
print1 = print1->next;
}
cout << "\n" << "The Second Polynomial is :" << endl;
while (print2->next != NULL) {
cout << print2->next->coenum << "X" << "^" << print2->next->index ;
if (print2->next->next != NULL)
cout << "+";
print2 = print2->next;
}
POLY P3;
P3 = Multiply(P1, P2);
polynomial *print3 = P3;
cout << "\n" << "The MUL of Polynomial is :" << endl;
while (print3->next != NULL) {
cout << print3->next->coenum << "X" << "^" << print3->next->index ;
if (print3->next->next != NULL)
cout << "+";
print3 = print3->next;
}
return 0;
}
主要参考: 《数据结构与算法》(第五版)张岩
《数据结构考研复习指导》(王道)
《某文章》