使用链表实现。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
float p;
unsigned int e;
struct node *next;
}polynomial,*p_polynomial;
p_polynomial poly_add(p_polynomial a, p_polynomial b)
{
p_polynomial p=a, q=b, t;
/*存在性*/
if (!a || !b)
{
printf("至少有一个多项式不存在,无法计算!");
return(NULL);
}
while (p->next || q->next)
{
if (!p->next)
{
p->next = q->next;
return(a);
}
if (!q->next)
{
return(a);
}
if (q->next->e == p->next->e)
{
p->next->p += q->next->p;
p = p->next;
q->next = q->next->next;
}
else
{
if (q->next->e < p->next->e)
{
t = q->next;
q->next = t->next;
t->next = p->next;
p->next = t;
p = p->next;
}
else
{
p = p->next;
while (p->next)
{
if (q->next->e > p->next->e)
p = p->next;
else
break;
}
if (!p->next)
{
t = q->next;
p->next->next = t;
return(a);
}
else
continue;
}
}
}
}
int display_polynomial(p_polynomial p)
{
if (!p)
{
printf("多项式不存在");
return(0);
}
p_polynomial t = p->next;
while (t)
{
printf("%f %d ", t->p, t->e);
t = t->next;
}
printf("\n");
return(1);
}
/*test*/
int main()
{
const int n1 = 5;
const int n2 = 7;
p_polynomial h1 = (p_polynomial)malloc(sizeof(polynomial));
p_polynomial h2 = (p_polynomial)malloc(sizeof(polynomial));
h1->next = NULL;
h2->next = NULL;
p_polynomial t = h1;
for (int i = 0; i < n1; i++)
{
t->next = (p_polynomial)malloc(sizeof(polynomial));
t->next->e = i;
t->next->p = i + 1;
t = t->next;
t->next = NULL;
}
t->next = (p_polynomial)malloc(sizeof(polynomial));
t->next->e =10;
t->next->p = 3;
t = t->next;
t->next = NULL;
t = h2;
for (int i = 0; i < n2; i++)
{
t->next = (p_polynomial)malloc(sizeof(polynomial));
t->next->e = i+3;
t->next->p = i + 1;
t = t->next;
t->next = NULL;
}
display_polynomial(h1);
display_polynomial(h2);
display_polynomial(poly_add(h1, h2));
while (true)
{
}
return(1);
}