c++实现输入两个稀疏一元多项式表达式,要求是指数有序的规范形式,然后对两个表达式求解
时间: 2023-12-14 07:39:24 浏览: 155
首先,我们需要确定一下稀疏一元多项式表达式的数据结构。可以使用一个结构体来表示每一项,包括系数和指数:
```c++
struct Item {
double coef; // 系数
int expn; // 指数
};
```
然后,我们可以使用链表来存储整个多项式表达式。对于稀疏多项式表达式来说,我们只需要存储那些系数不为0的项即可。
```c++
struct Node {
Item item;
Node* next;
};
struct Poly {
Node* head;
};
```
接下来,我们就可以编写代码实现输入两个稀疏一元多项式表达式了。假设我们已经输入了两个多项式的项数,以及每一项的系数和指数,分别存储在数组 `coef1[]`、`expn1[]`、`coef2[]`、`expn2[]` 中。那么,可以这样实现输入多项式的函数:
```c++
void createPoly(Poly& poly, double coef[], int expn[], int n) {
Node* p = new Node();
p->next = nullptr;
poly.head = p;
for (int i = 0; i < n; i++) {
if (coef[i] != 0) {
Node* q = new Node();
q->item.coef = coef[i];
q->item.expn = expn[i];
q->next = nullptr;
p->next = q;
p = q;
}
}
}
```
接下来,我们需要实现对两个多项式求解的函数。可以定义一个新的多项式来存储结果,然后遍历两个多项式的链表,按照指数从小到大的顺序合并项。
```c++
void addPoly(Poly& result, const Poly& poly1, const Poly& poly2) {
Node* p = poly1.head->next;
Node* q = poly2.head->next;
Node* r = new Node();
r->next = nullptr;
result.head = r;
while (p != nullptr && q != nullptr) {
Node* s = new Node();
if (p->item.expn < q->item.expn) {
s->item = p->item;
p = p->next;
} else if (p->item.expn > q->item.expn) {
s->item = q->item;
q = q->next;
} else {
s->item.coef = p->item.coef + q->item.coef;
s->item.expn = p->item.expn;
p = p->next;
q = q->next;
}
s->next = r->next;
r->next = s;
r = s;
}
while (p != nullptr) {
Node* s = new Node();
s->item = p->item;
s->next = r->next;
r->next = s;
r = s;
p = p->next;
}
while (q != nullptr) {
Node* s = new Node();
s->item = q->item;
s->next = r->next;
r->next = s;
r = s;
q = q->next;
}
}
```
最后,我们可以在主函数中调用这两个函数来实现对两个多项式的求解了:
```c++
int main() {
int n1, n2;
double coef1[MAXSIZE], coef2[MAXSIZE];
int expn1[MAXSIZE], expn2[MAXSIZE];
cin >> n1;
for (int i = 0; i < n1; i++) {
cin >> coef1[i] >> expn1[i];
}
cin >> n2;
for (int i = 0; i < n2; i++) {
cin >> coef2[i] >> expn2[i];
}
Poly poly1, poly2, result;
createPoly(poly1, coef1, expn1, n1);
createPoly(poly2, coef2, expn2, n2);
addPoly(result, poly1, poly2);
Node* p = result.head->next;
while (p != nullptr) {
cout << p->item.coef << " " << p->item.expn << endl;
p = p->next;
}
return 0;
}
```
完整代码如下:
阅读全文