# Program to sum two polynomials using Linked list in C.

```#include<stdio.h>
typedef struct poly
{
int coeff;
int powx;
int powy;
int powz;
struct poly *next;
} poly;

FILE *fp1, *fp2;
poly *p1 = NULL;
poly *p2 = NULL;
poly *p3 = NULL;

poly *create (FILE *);
void print (poly *);
poly *add (poly *, poly *);
int cmp (int, int, int);

main ()
{
fp1 = fopen ("py1.c", "r");
if (fp1 == NULL)
{
puts ("Cannot open file");
exit (0);
}
p1 = create (fp1);
printf ("\nFirst Polynomial Is:\n");
print (p1);
fp2 = fopen ("py2.c", "r");
if (fp2 == NULL)
{
puts ("Cannot open file");
exit (0);
}
p2 = create (fp2);
printf ("\nSecond Polynomial Is:\n");
print (p2);
printf ("\nTheir Sum Is:\n");
print (p3);
}

poly *
create (FILE * fp)
{
poly *p = NULL;
int coeff, powx, powy, powz;
poly *q, *t;
while (fscanf (fp, "%d %d %d %d", &coeff, &powx, &powy, &powz) != EOF)
{
q = (poly *) malloc (sizeof (poly));
q->coeff = coeff;
q->powx = powx;
q->powy = powy;
q->powz = powz;
q->next = NULL;
if (p == NULL)
{
t = q;
p = q;
}
else
t->next = q;
t = q;
}
return p;
}

void
print (poly * p)
{
poly *q;
q = p;
while (p != NULL)
{
printf ("\t%d*%d,%d,%d", p->coeff, p->powx, p->powy, p->powz);
p = p->next;
}
p = q;
printf ("\n");
}

poly *
add (poly * a, poly * b)
{
int val1, val2, newcoeff, newpowx, newpowy, newpowz;
poly *p, *q, *r, *s, *z;
p = a;
q = b;
r = NULL;
while ((p != NULL) && (q != NULL))
{
val1 = cmp (p->powx, p->powy, p->powz);
val2 = cmp (q->powx, q->powy, q->powz);
if (val1 == val2)
{
newcoeff = p->coeff + q->coeff;
newpowx = p->powx;
newpowy = p->powy;
newpowz = p->powz;
p = p->next;
q = q->next;
}
else if (val1 > val2)
{
newcoeff = q->coeff;
newpowx = q->powx;
newpowy = q->powy;
newpowz = q->powz;
q = q->next;
}
else
{
newcoeff = p->coeff;
newpowx = p->powx;
newpowy = p->powy;
newpowz = p->powz;
p = p->next;
}
if (newcoeff != 0)
{
s = (poly *) malloc (sizeof (poly));
s->coeff = newcoeff;
s->powx = newpowx;
s->powy = newpowy;
s->powz = newpowz;
if (r == NULL)
z = s;
else
r->next = s;
r = s;
s->next = NULL;
}
}
if (p == NULL)
{
while (q != NULL)
{
if (q->coeff != 0)
{
s = (poly *) malloc (sizeof (poly));
s->coeff = q->coeff;
s->powx = q->powx;
s->powy = q->powy;
s->powz = q->powz;
if (r == NULL)
z = s;
else
r->next = s;
r = s;
s->next = NULL;
q = q->next;
}
else
q = q->next;
}
}
else
{
while (p != NULL)
{
if (p->coeff != 0)
{
s = (poly *) malloc (sizeof (poly));
s->coeff = p->coeff;
s->powx = p->powx;
s->powy = p->powy;
s->powz = p->powz;
if (r == NULL)
z = s;
else
r->next = s;
r = s;
s->next = NULL;
p = p->next;
}
else
p = p->next;
}
}
return z;
}

int
cmp (int x, int y, int z)
{
return ((1000 * x) + (100 * y) + (10 * z));
}```