--- In [email protected], "tusarkant sahoo" <[EMAIL PROTECTED]>
wrote:
>
> Am a noob in data structure in C Plz Help me.
>
> (1) WAP to add two polynomials using linked list ?
//Polynomial Addition
#include<stdio.h>
#include<conio.h>
#define MAX 10
struct term
{
int coeff;
int exp;
};
struct poly
{
struct term t[10];
int noofterm;
};
void Initialize(struct poly *p)
{
int i;
p->noofterm=0;
for(i=0;i<MAX;i++)
{
p->t[i].coeff=0;
p->t[i].exp=0;
}
}
void PolyInsert(struct poly *p,int c,int e)
{
p->t[p->noofterm].coeff=c;
p->t[p->noofterm].exp=e;
(p->noofterm)++;
}
void PolyAdd(struct poly *p1,struct poly *p2,struct poly *p3)
{
int i=0,j=0;
while(1)
{
if(p1->t[i].coeff==0 && p2->t[j].coeff==0)
break;
if(p1->t[i].exp==p2->t[j].exp)
{
p3->t[p3->noofterm].coeff=p1->t[i].coeff+p2-
>t[j].coeff;
p3->t[p3->noofterm].exp=p1->t[i].exp;
i++,j++;
}
else
{
if(p1->t[i].exp>p2->t[j].exp)
{
p3->t[p3->noofterm].coeff=p1->t
[i].coeff;
p3->t[p3->noofterm].exp=p1->t[i].exp;
i++;
}
else
{
p3->t[p3->noofterm].coeff=p2->t
[j].coeff;
p3->t[p3->noofterm].exp=p2->t[j].exp;
j++;
}
}
(p3->noofterm)++;
}
}
void Display(struct poly *p)
{
int i;
for(i=0;i<p->noofterm;i++)
{
if(p->t[i].exp!=0)
{
printf("%d*^%d",p->t[i].coeff,p->t[i].exp);
if(p->noofterm-(i+1))
printf("+");
}
else
printf("%d",p->t[i].coeff);
}
}
void main()
{
struct poly p1,p2,p3;
clrscr();
Initialize(&p1);
Initialize(&p2);
Initialize(&p3);
printf("\nFirst Polynominal =>");
PolyInsert(&p1,3,8);
PolyInsert(&p1,4,6);
PolyInsert(&p1,5,4);
PolyInsert(&p1,3,3);
PolyInsert(&p1,4,0);
Display(&p1);
printf("\nSecond Polynominal =>");
PolyInsert(&p2,2,7);
PolyInsert(&p2,3,6);
PolyInsert(&p2,4,5);
PolyInsert(&p2,3,3);
PolyInsert(&p2,2,0);
Display(&p2);
printf("\nAdded Third Polynominal =>");
PolyAdd(&p1,&p2,&p3);
Display(&p3);
getch();
}
/*
Jugal kishor panchal
MCA (Pune)
*/