1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
#include<iostream>
using namespace std;
class polyll
{
int co;
int exp;
polyll *next;
public:
polyll(int co1,int exp1,polyll *link)
{
co=co1;
exp=exp1;
next=link;
}
polyll *addterm(int co,int exp)
{
if(!this)
return new polyll(co,exp,NULL);
//to enter terms in descendin order of exp
if(this->exp < exp)
new polyll(co,exp,NULL);
polyll *curr=this;
while(curr->next && curr->next->exp > exp)
curr=curr->next;
// Missing a return here
}
friend polyll* addpoly( polyll *p1,polyll *p2);
void display(polyll *l)
{
if(l)
{
cout<<l->co<<"x^"<<l->exp<<"+";
display(l->next);
}
}
int count(polyll *l)
{
int n=0;
while(l)
{
l=l->next;
n++;
}
return n;
}
};
polyll* addpoly ( polyll *p1,polyll *p2)
{
polyll *p3;
polyll *p3Head;
p3Head=new polyll(0,0,NULL);
p3=p3Head;
int i,j;
i=0;j=0;
while(p1 && p2)
{
if(p1->exp==p2->exp)
{
int c=p1->co+p2->co;
if(c)
p3->next=new polyll(c,p1->exp,NULL);
p1=p1->next;
p2=p2->next;
p3=p3->next;
i++;
j++;
}
else if(p1->exp < p2->exp)
{
p3->next=new polyll(p2->co,p2->exp,NULL);
p2=p2->next;
p3=p3->next;
j++;
}
else
{
p3->next=new polyll(p1->co,p2->exp,NULL);
p1=p1->next;
p3=p3->next;
i++;
}
}
while(i< p1->count(p1))
{
p3->next=new polyll(p1->co,p1->exp,NULL);
p1=p1->next;
i++;
}
while(j< p2->count(p2))
{
p3->next=new polyll(p2->co,p2->exp,NULL);
p2=p2->next;
j++;
}
return p3Head->next; // error: 'p3head' was not declared in this scope
}
int main()
{
polyll *p1=NULL;
polyll *p2=NULL;
polyll *p3=NULL;
p1=p1->addterm(2,4);
p1=p1->addterm(3,3);
p2=p2->addterm(2,3);
p2=p2->addterm(2,2);
p2=p2->addterm(1,1);
p3=addpoly(p1,p2);
p3->display(p2);
return 0;
}
|