Thursday, 30 November 2017

POLYNOMIAL ADDITION USING LINKED LIST IN C

#include <stdio.h>
#include <stdlib.h>
struct Node{
int co,po;
struct Node*plink;
};
struct head{
struct Node*pfirst;
};
struct head *pl1,*pl2,*pl3;
void createlist(struct head*);
struct Node* create();
struct Node* mem(int,int);
void disp(struct head *);
void insert(struct head*,struct Node*);
void Add(struct head*,struct head*,struct head*);
int main() {
pl1=(struct head*)malloc(sizeof(struct head));
pl1->pfirst=NULL;
pl2=(struct head*)malloc(sizeof(struct head));
pl2->pfirst=NULL;
pl3=(struct head*)malloc(sizeof(struct head));
pl3->pfirst=NULL;
if(pl1&&pl2&&pl3){
printf("  enter poly exp1:\n");
createlist(pl1);
printf("  enter poly exp2:\n");
createlist(pl2);
printf("poly 1:\n");
disp(pl1);
printf("\n");
printf("poly 2:\n");
disp(pl2);
printf("\n");
Add(pl1,pl2,pl3);
printf("poly exp after adding is\n");
disp(pl3);

}
return 0;
}
struct Node* create(){
struct Node* ptemp=(struct Node*)malloc(sizeof(struct Node));
if(!ptemp) return NULL;
else{
printf("enter Coefficient,power\n");scanf("%d%d",&(ptemp->co),&(ptemp->po));ptemp->plink=NULL;return ptemp;
}
}
void createlist(struct head*ptr){struct Node* ptemp=NULL;
int i,n=0;
printf("enter highest power of expression\n");
scanf("%d",&n);for(i=0;i<=n;i++)
{
ptemp=create();
insert(ptr,ptemp);
}
return;}
void insert(struct head*ptr1,struct Node*p1)
{
if(!p1){
printf("no memory \n");
return;
}
else{
struct Node *ptemp1=NULL;
if(!(ptr1->pfirst)){
ptr1->pfirst=p1;
}
else
{
ptemp1=ptr1->pfirst;
while(ptemp1->plink)
ptemp1=ptemp1->plink;
ptemp1->plink=p1;
}
return;
}
}
struct Node* mem(int c,int p){
struct Node* ptr=(struct Node*)malloc(sizeof(struct Node));
if(!ptr)
return NULL;
else{
ptr->co=c;
ptr->po=p;ptr->plink=NULL;return ptr;
}}
void disp(struct head*ptr2){
struct Node*ptemp=NULL;
if(!ptr2->pfirst){
printf("empty polynomial\n");return;
}
else{
int i=0;
ptemp=ptr2->pfirst;
do{
if(((ptemp->co)>0)&&i!=0){
printf("+");
}
printf("%dx^%d",ptemp->co,ptemp->po);
ptemp=ptemp->plink;
i++;
}while(ptemp);
}
return;
}
void Add(struct head*pt1,struct head*pt2,struct head*pt3){
struct Node *ptl1=NULL,*ptl2=NULL,*ptl3=NULL;
ptl1=pt1->pfirst; ptl2=pt2->pfirst;
int a;
while((ptl1)&&(ptl2)){
if((ptl1->po)>(ptl2->po)){
ptl3=mem(ptl1->po,ptl1->co);
ptl1=ptl1->plink;
insert(pt3,ptl3);
}
else if((ptl2->po)>(ptl1->po)){
ptl3=mem(ptl2->po,ptl2->co);
ptl2=ptl2->plink;
insert(pt3,ptl3);
}
else{
a=(ptl1->co)+(ptl2->co);
ptl3=mem(a,ptl1->po);
ptl1=ptl1->plink; ptl2=ptl2->plink;insert(pt3,ptl3);
}
}
while(ptl1){
ptl3=mem(ptl1->po,ptl1->co);
ptl1=ptl1->plink;
insert(pt3,ptl3);
}
while(ptl2){
ptl3=mem(ptl2->po,ptl2->co);
ptl2=ptl2->plink;
insert(pt3,ptl3);
}
return;
} 🔜


No comments:

Post a Comment

FERMATS LITTLE THEOREM

import java.math.*; import java.io.*; import java.util.Scanner; public class Main { public static void main(String[] args) {    Sca...