#include<bits/stdc++.h>
using namespace std;
typedef struct LNode {
float coef;//系数
int expn;
LNode* next;
}LNode,*Linklist;
void Iinitlist(Linklist& L)//初始化
{
L = new LNode;
L->next = NULL;
}
//冒泡法单链表
void sortlist(Linklist& L)
{
Linklist wt, nt, lastnt = 0;
for (wt = L->next; wt->next != NULL; wt = wt->next)
{
for (nt = L->next; nt->next != lastnt; nt = nt->next)
{
if (nt->expn > nt->next->expn)
{
int temp, Temp;
temp = nt->coef;
Temp = nt->expn;
nt->expn = nt->next->expn;
nt->coef = nt->next->coef;
nt->next->expn = Temp;
nt->next->coef = temp;
}
}
}
}
void createlist(Linklist& L)//尾插法
{
Iinitlist(L);
LNode* s, * p=L;
printf("请输入这个多项式有多少项:");
int n;
scanf("%d", &n);
if (n < 0)
{
printf("请重新输入多项式有几项:");
scanf("%d", &n);
}
for (int i = 0; i < n; i++)
{
s = new LNode;
printf("请输入第%d项的系数和指数分别为:", i + 1);
scanf("%f %d", &s->coef, &s->expn);
if (!s->coef)
{
printf("%f %d", &s->coef, &s->expn);
}
p->next = s;
p = s;
}
p->next = NULL;
}
Linklist add_list(Linklist& L, Linklist& M)
{
LNode* p = L->next, * q = M->next, * r, * s;
r = L;
while (p && q)
{
if (p->expn < q->expn)
{
r->next = p;
p = p->next;
r = r->next;
}
else if (p->expn > q->expn)
{
r->next = q;
r = r->next;
q = q->next;
}
else
{
float sum = p->coef + q->coef;
if (sum != 0.0)
{
p->coef = sum;
r->next = p;
r = r->next;
p = p->next;
s = q;
q = q->next;
free(s);
}
else {
s = p;
p = p->next;
free(s);
s = q;
q = q->next;
free(s);
}
}
}
r->next = p ? p : q;
free(M);
sortlist(L);
return L;
}
Linklist Multilist(Linklist &L,Linklist &M)
{
LNode* p, * q, * s,*t;
p = L->next;
q = M->next;
Linklist K;
Iinitlist(K);
s = K;
int a = 0;
while (p)
{
if (a == 0)
{
while (q) {
LNode* r;
r = new LNode;
float c = p->coef * q->coef;
int b = p->expn+q->expn;
r->coef = c;
r->expn = b;
s->next = r;
r->next = NULL;
s = r;
q = q->next;
}
}
else {
Linklist L0;
Iinitlist(L0);
t = L0;
while (q)
{
LNode* l;
l = new LNode;
l->coef = p->coef*q->coef;
l->expn = p->expn + q->expn;
t->next = l;
l->next = NULL;
t = l;
q = q->next;
}
K = add_list(K, L0);
}
p = p->next;
q = M->next;
a = 1;
}
return K;
}
void printf_list(Linklist& K)
{
LNode* s = K->next;
while (s)
{
if (s->coef != 1.0)//判断是否系数等于1,则省略不写
{
if (s->expn != 0)//判断是否指数等于0则x的0次方等于1
printf("%.f*x~%d", s->coef, s->expn);
else
printf("%d", s->coef);
}
else {
if (s->expn != 0)//判断是否指数等于0则x的0次方等于1
printf("x~%d", s->expn);
else
printf("%d", s->coef);
}
if (s->next != NULL && s->coef > 0)//判断是否到链表尾,其系数若小于0则可省略不写
printf("+");
s = s->next;
}
printf("\n");
}
int main()
{
Linklist L, M, K;
createlist(L);
printf("第一个多项式为:\n");
printf_list(L);
createlist(M);
printf("第二个多项式为:\n");
printf_list(M);
K= Multilist(L, M);
printf("两个多项式相乘为:\n");
printf_list(K);
}
多项式乘法
最新推荐文章于 2024-11-09 20:38:27 发布