/* Add two Polynomials Using Linked list */
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{ int power;
float coeff;
struct node *next;
}node;
node * insert(node *head,int power,float coeff);
node * create();
node * padd(node *head1,node *head2);
void print(node *head);
int main()
{
node *head1,*head2,*head3;
int op;
float value,x;
head1=create();
head2=create();
// print(head1);
// print(head2);
//add
head3=padd(head1,head2);
print(head3);
}
node * insert(node *head,int power,float coeff)
{ node *p,*q;
/*terms are store in increasing order of power*/
/*pointer is used to locate the correct place of insertion.
pointer p is used to store the address of the node created for
the current term*/
p=(node*)malloc(sizeof(node));
p->power=power;p->coeff=coeff;
p->next=NULL;
if(head==NULL)
return(p);
else
if(power<head->power)
{ p->next=head;
return(p);
}
else
{ q=head;
while(q->next!=NULL && power>=q->next->power)
q=q->next;
p->next=q->next;
q->next=p;
/*if the node pointed by p and q have same power,merge two nodes*/
if(q->power==p->power)
{ q->coeff=q->coeff+p->coeff;
q->next=p->next;
free(p);
}
return(head);
}
}
node * create()
{ int n,i,power;
float coeff;
node *head;
head=NULL;
printf("\nEnter polynomial:");
printf("\nEnter No. of Terms:");
scanf("%d",&n);
printf("\nenter a term as a tuple of (power,coefficient)");
for(i=1;i<=n;i++)
{ scanf("%d%f",&power,&coeff);
head=insert(head,power,coeff);
}
return(head);
}
node * padd(node *head1,node *head2)
{ node *head=NULL;
int power;float coeff;
while(head1 != NULL && head2 != NULL)
{ if(head1->power < head2->power)
{ head=insert(head,head1->power,head1->coeff);
head1=head1->next;
continue;
}
if(head2->power < head1->power)
{ head=insert(head,head2->power,head2->coeff);
head2=head2->next;
continue;
}
head=insert(head,head1->power,head1->coeff+head2->coeff);
head1=head1->next;
head2=head2->next;
}
while(head1!=NULL)
{head=insert(head,head1->power,head1->coeff);
head1=head1->next;
}
while(head2!=NULL)
{head=insert(head,head2->power,head2->coeff);
head2=head2->next;
}
return(head);
}
void print(node *head)
{ printf("\n");
while(head!=NULL)
{
printf("%6.2fX^%d ",head->coeff,head->power);
head=head->next;
}
}
No comments:
Post a Comment