#include<iostream>
using namespace std;
typedef struct lnode
{
float coe;//系数
int exp;//指数
struct lnode* next;
}node;
node* Create(int n); //创建链表
void Output(node* head); //输出
void Add(node* head_c, float COE, int EXP); //合并链表
node* Multi(node* head_a, node* head_b); //链表乘法
int main()
{
cout << "---降幂多项式相乘---" << endl;
int n1, n2;
cout << "请输入多项式A的项数:";
cin >> n1;
node* head_a = Create(n1);
cout << "A = ";
Output(head_a);
cout << "请输入多项式B的项数:";
cin >> n2;
node* head_b = Create(n2);
cout << "B = ";
Output(head_b);
node* head_c = Multi(head_a, head_b);
cout << "C = A * B = ";
Output(head_c);
return 0;
}
node* Create(int n)
{
node* head, * p, * q;
head = (node*)malloc(sizeof(node));
if (!head)
{
cout << "头结点开辟失败!" << endl;
exit(1);
}
head->next = NULL;
q = head;
int i = 1;
while (n--)
{
if (p = (node*)malloc(sizeof(node)))
{
cout << "请输入第" << i << "项的系数和指数:";
cin >> p->coe >> p->exp;
p->next = NULL;
q -> next = p;
q = p;
i++;
}
else
{
cout << "结点开辟失败!" << endl;
exit(1);
}
}
return head;
}
void Output(node* head)
{
node* p = head->next;
while (p->next != NULL)
{
cout << p->coe << "x^" << p->exp << "+";
p = p->next;
}
cout << p->coe << "x^" << p->exp << endl;
}
void Add(node* head_c, float COE, int EXP)
{
node* r = head_c;
if (!r->next)//如果是c链表的第一项,则直接将新项添加为第一项
{
node* s;
if (s = (node*)malloc(sizeof(node)))
{
s->coe = COE;
s->exp = EXP;
s->next = NULL;
r->next = s;
r = s;
}
else
{
cout << "头结点分配失败!" << endl;
exit(1);
}
}
else//如果是c链表的其他项
{
while (r->next && r->next->exp > EXP)
r = r->next;
if (!r->next && r->exp > EXP)//直接加到最后
{
node* s;
if (s = (node*)malloc(sizeof(node)))
{
s->coe = COE;
s->exp = EXP;
s->next = NULL;
r->next = s;
r = s;
}
else
{
cout << "头结点分配失败!" << endl;
exit(1);
}
}
else if (!r->next && r->exp == EXP)//合并最后一项
{
r->coe += COE;
}
else if (r->next->exp == EXP)//此时将指数相同的这两项合并
{
r->next->coe += COE;
}
else if (r->next->exp<EXP && r->exp>EXP)//在c链表中开辟新结点
{
node* s;
if (s = (node*)malloc(sizeof(node)))
{
s->coe = COE;
s->exp = EXP;
s->next = r->next;
r->next = s;
}
else
{
cout << "头结点分配失败!" << endl;
exit(1);
}
}
}
}
node* Multi(node* head_a, node* head_b)
{
node* head_c = (node*)malloc(sizeof(node));
if (!head_c)
{
cout << "头结点分配失败!" << endl;
exit(1);
}
head_c->next = NULL;
node* p = head_a->next;
float COE;
int EXP;
while (p) //双重循环进行多项式乘法
{
node* q = head_b->next;
while (q)
{
COE = p->coe * q->coe;
EXP = p->exp + q->exp;
Add(head_c, COE, EXP);
q = q->next;
}
p = p->next;
}
return head_c;
}