![552111031bfb2fc2e5101f1a3388c399.png](https://img-blog.csdnimg.cn/img_convert/552111031bfb2fc2e5101f1a3388c399.png)
感觉对链表的理解已经基本木得问题了o(* ̄▽ ̄*)ブ
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0
。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
思路:分四个函数:读,加,乘,写。
其中乘法可分为每一项与另一个多项式分别相乘再相加。
加法中会出现零项,需特殊处理。
其实C++不需要
Polynomial* head = (Polynomial*)malloc(sizeof(Polynomial));
这么麻烦,用
Polynomial* head =new Polynomial;
就行了。。但是我用C太久了,没缓过劲来≧ ﹏ ≦
还有下次写函数,可以把内容写主函数后面,避免头重脚轻,影响浏览。
#include <iostream>
using namespace std;
struct Polynomial
{
int coef;
int index;
Polynomial* next;
};
Polynomial* Read()
{
Polynomial* head = (Polynomial*)malloc(sizeof(Polynomial));
head->next = NULL;
int n;
cin >> n;
Polynomial* last = head, * temp;
for (int i = 0; i < n; i++)
{
temp= (Polynomial*)malloc(sizeof(Polynomial));
cin >> temp->coef >> temp->index;
temp->next = NULL;
last->next = temp;
last = last->next;
}
return head;
}
Polynomial* Add(Polynomial* list1, Polynomial* list2)
{
Polynomial* head = (Polynomial*)malloc(sizeof(Polynomial));
head->next = NULL;
Polynomial* last = head, * temp, * p1 = list1->next, * p2 = list2->next;
while (p1 && p2)
{
temp = (Polynomial*)malloc(sizeof(Polynomial));
temp->next = NULL;
if (p1->index > p2->index)
{
temp->coef = p1->coef;
temp->index = p1->index;
p1 = p1->next;
}
else if (p1->index < p2->index)
{
temp->coef = p2->coef;
temp->index = p2->index;
p2 = p2->next;
}
else
{
if (p1->coef + p2->coef != 0)
{
temp->coef = p1->coef + p2->coef;
temp->index = p1->index;
}
else
{
free(temp);
temp = NULL;
}
p1 = p1->next;
p2 = p2->next;
}
if (temp)
{
last->next = temp;
last = last->next;
}
}
if (p1) last->next = p1;
if (p2) last->next = p2;
return head;
}
Polynomial* SimpleMul(Polynomial* list1, Polynomial* list2)
{
Polynomial* head = (Polynomial*)malloc(sizeof(Polynomial));
head->next = NULL;
Polynomial* last = head, * temp, * p1 = list1, * p2 = list2->next;
while (p2)
{
temp = (Polynomial*)malloc(sizeof(Polynomial));
temp->next = NULL;
temp->coef = p1->coef * p2->coef;
temp->index = p1->index + p2->index;
last->next = temp;
last = last->next;
p2 = p2->next;
}
return head;
}
Polynomial* Mul(Polynomial* list1, Polynomial* list2)
{
Polynomial* head = (Polynomial*)malloc(sizeof(Polynomial));
head->next = NULL;
Polynomial* temp;
for (Polynomial* p1 = list1->next, *p2 = list2; p1; p1=p1->next)
{
temp = SimpleMul(p1, p2);
head = Add(head, temp);
}
return head;
}
void Write(Polynomial* L)
{
Polynomial* p = L->next;
if (!p)
cout << "0 0";
for (; p; p=p->next)
{
cout << p->coef << " " << p->index;
if (p->next)
cout << " ";
}
cout << endl;
}
int main()
{
Polynomial* list1, *list2;
list1= Read();
list2 = Read();
Polynomial* add, * mul;
add = Add(list1, list2);
mul = Mul(list1, list2);
Write(mul);
Write(add);
return 0;
}