Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- include<stdio.h>
- #include<malloc.h>
- struct poly
- {
- int co;
- int exp;
- struct poly *ptr;
- };
- struct poly * Addelement(struct poly *,int,int);
- struct poly * add(struct poly *,struct poly *);
- void display(struct poly *);
- int main()
- {
- int num1,co,exp,num2,i;
- struct poly *p1,*p2,*p3;
- p1=NULL;
- p2=NULL;
- p3=NULL;
- printf(" \n The number of elements to be added to the 1st list ");
- scanf("%d",&num1);
- for(i=1;i<=num1;i++)
- {
- printf("\n Enter the Elements of 1st polynomial and coeff \n ");
- scanf("%d %d",&co,&exp);
- p1=Addelement(p1,co,exp);
- }
- printf(" \n The number of elements to be added to the 2nd list ");
- scanf("%d",&num2);
- for(i=1;i<=num2;i++)
- {
- printf("\n Enter the Elements of 2nd polynomial and coeff \n ");
- scanf("%d %d",&co,&exp);
- p2=Addelement(p2,co,exp);
- }
- printf("\n The elements of first polynomial are ");
- display(p1);
- printf("\n The elements of second polynomial are ");
- display(p2);
- p3=add(p1,p2);
- printf("\n The Added polynomial is \n");
- display(p3);
- }
- struct poly * Addelement(struct poly *head,int co,int exp)
- {
- struct poly *newnode;
- newnode=(struct poly *)malloc(sizeof(struct poly));
- newnode->co=co;
- newnode->exp=exp;
- if(head==NULL)
- {
- newnode->ptr=NULL;
- return newnode;
- }
- else
- {
- newnode->ptr=head;
- return newnode;
- }
- }
- void display(struct poly *p3)
- {
- if(p3==NULL)
- {
- printf("\n The list is empty \n");
- }
- while(p3!=NULL)
- {
- printf(" %dx^%d+ ",p3->co,p3->exp);
- p3=p3->ptr;
- }
- }
- struct poly * add(struct poly *p1,struct poly *p2)
- {
- struct poly *p3,*temp;
- p3=NULL;
- if(p1==NULL&&p2==NULL)
- {
- printf("\n The list is empty \n");
- }
- while(p1!=NULL&&p2!=NULL)
- {
- temp=(struct poly *)malloc(sizeof(struct poly));
- if(p3==NULL)
- {
- temp->ptr=NULL;
- p3=temp;
- }
- else
- {
- temp->ptr=p3;
- p3=temp;
- }
- if(p1->exp>p2->exp)
- {
- temp->co=p1->co;
- temp->exp=p1->exp;
- p1=p1->ptr;
- }
- else if(p2->exp>p1->exp)
- {
- temp->co=p2->co;
- temp->exp=p2->exp;
- p2=p2->ptr;
- }
- else if(p1->exp==p2->exp)
- {
- temp->co=p1->co+p2->co;
- temp->exp=p1->exp;
- p1=p1->ptr;
- p2=p2->ptr;
- }
- }
- while(p1!=NULL)
- {
- temp=(struct poly *)malloc(sizeof(struct poly));
- temp->co=p1->co;
- temp->exp=p1->exp;
- temp->ptr=p3;
- p3=temp;
- p1=p1->ptr;
- }
- while(p2!=NULL)
- {
- temp=(struct poly *)malloc(sizeof(struct poly));
- temp->co=p2->co;
- temp->exp=p2->exp;
- temp->ptr=p3;
- p3=temp;
- p2=p2->ptr;
- }
- return p3;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement