Wednesday, March 3, 2010

ds-addition of polynomial

//addition of two polynomial
#include "stdio.h"
#include "conio.h"
#include "alloc.h"
#include "stdlib.h"
typedef struct node
{
int px,py,pz,co;
struct node *next;
}node;
void insert(node **,int,int,int,int);
void display(node *);
void copy(node **,node **);
void addpoly(node *,node *,node **);
void main()
{
node *p1=NULL,*p2=NULL,*p3=NULL;
clrscr();
insert(&p1,1,1,1,4);
insert(&p1,1,1,2,1);
insert(&p1,1,2,1,2);
insert(&p1,2,1,1,3);
display(p1);
insert(&p2,1,1,1,3);
insert(&p2,1,1,2,5);
insert(&p2,1,2,1,2);
display(p2);
addpoly(p1,p2,&p3);
printf("---------------------------------------------\n");
display(p3);
getch();
}
void insert(node **p,int x,int y,int z,int c)
{
node *newnode=(node *)malloc(sizeof(node));
newnode->px=x;
newnode->py=y;
newnode->pz=z;
newnode->co=c;
if(*p==NULL){
newnode->next=NULL;
*p=newnode; }
else {
newnode->next=*p;
*p=newnode; }
}
void display(node *p)
{
while(p!=NULL) {
printf("%dX^%dY^%dZ^%d + ",p->co,p->px,p->py,p->pz);
p=p->next; }
printf("\n");
}
void addpoly(node *p1,node *p2,node **p3)
{
int a1,a2,b1,b2,c1,c2,d1,d2;
while((p1!=NULL)&&(p2!=NULL)){
a1=p1->px;a2=p2->px;
b1=p1->py;b2=p2->py;
c1=p1->pz;c2=p2->pz;
d1=p1->co;d2=p2->co;
if((a1==a2)&&(b1==b2)&&(c1==c2))
{ if((d1+d2)!=0)
insert(p3,a1,b1,c1,d1+d2);
p1=p1->next;
p2=p2->next;
}
else if((a1>a2)(a1==a2)&&(b1>b2)(a1==a2)&&(b1==b2)&&(c1>c2))
{insert(p3,a1,b1,c1,d1);
p1=p1->next; }
else {
insert(p3,a2,b2,c2,d2);
p2=p2->next; } }
if(p1!=NULL)
copy(&p1,p3);
else{
if(p2!=NULL){
copy(&p2,p3);
*p3=(*p3)->next;
while(p3!=NULL) {
(*p3)->co=-((*p3)->co);
*p3=p2;}}
}
}
void copy(node **first,node **begin)
{
node *t,*p;
t=*first;
while(t!=NULL){
node *newnode=(node *)malloc(sizeof(node));
newnode->px=t->px;
newnode->next=NULL;
if(*begin==NULL){
*begin=newnode; }
else {
p=*begin;
while((p->next)!=NULL)
p=p->next;
p->next=newnode;
}
t=t->next; }
}

No comments:

Post a Comment