#include<iostream.h>
class Node
{
public:
int coeff;
int expo;
Node *next;
};
class Polynomial
{
Node *root;
public:
Polynomial();
void readPoly();
Polynomial add(Polynomial p);
void display();
};
Polynomial :: Polynomial()
{
root=NULL;
}
void Polynomial :: readPoly()
{
char ch = 'y';
while (ch == 'y')
{
Node *newNode=new Node;;
cout<<"\nEnter coefficient:";
cin>>newNode->coeff;
cout<<"\nEnter exponent:";
cin>>newNode->expo;
newNode->next = NULL;
if (root == NULL)
root = newNode;
else
{
Node *prev, *curr;
curr = root;
prev = NULL;
while ((curr != NULL) && (curr->expo > newNode->expo))
{
prev = curr;
curr = curr->next;
}
if ((curr != NULL) && (curr->expo == newNode->expo))
{
curr->coeff = curr->coeff + newNode->coeff;
cout<<"\nDo you want to continue? (y/n):";
cin>>ch;
if (ch == 'y')
continue;
else
return;
}
if (prev == NULL)
{
newNode->next = root;
root = newNode;
}
else
{
prev->next = newNode;
newNode->next = curr;
}
}
cout<<"\nDo you want to continue? (y/n):";
cin>>ch;
}
}
Polynomial Polynomial :: add(Polynomial p)
{
Node *ptr1,*ptr2;
Polynomial result;
ptr1 = root;
ptr2 = p.root;
result.root = NULL;
while ((ptr1 != NULL) && (ptr2 != NULL))
{
Node *newNode=new Node;;
newNode->next = NULL;
if (ptr1->expo > ptr2->expo)
{
newNode->coeff = ptr1->coeff;
newNode->expo = ptr1->expo;
ptr1 = ptr1->next;
}
else if (ptr2->expo > ptr1->expo)
{
newNode->coeff = ptr2->coeff;
newNode->expo = ptr2->expo;
ptr2 = ptr2->next;
}
else
{
newNode->coeff = ptr1->coeff + ptr2->coeff;
newNode->expo = ptr1->expo;
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
if (result.root == NULL)
result.root = newNode;
else
{
Node *ptr3;
ptr3 = result.root;
while (ptr3->next != NULL)
ptr3 = ptr3->next;
ptr3->next = newNode;
}
}
while (ptr1 != NULL)
{
Node *newNode;
newNode->next = NULL;
newNode->coeff = ptr1->coeff;
newNode->expo = ptr1->expo;
Node *ptr3;
ptr3 = result.root;
while (ptr3->next != NULL)
ptr3 = ptr3->next;
ptr3->next = newNode;
ptr1 = ptr1->next;
}
while (ptr2 != NULL)
{
Node *newNode;
newNode->next = NULL;
newNode->coeff = ptr2->coeff;
newNode->expo = ptr2->expo;
Node *ptr3;
ptr3 = result.root;
while (ptr3->next != NULL)
ptr3 = ptr3->next;
ptr3->next = newNode;
ptr2 = ptr2->next;
}
return result;
}
void Polynomial :: display()
{
Node *ptr;
ptr= root;
while (ptr!= NULL)
{
if ((ptr != root) && (ptr->coeff >= 0))
cout<<"+";
cout<<ptr->coeff << "x^" << ptr->expo << " ";
ptr = ptr->next;
}
}
class PolynomialAddition
{
};
void main()
{
Polynomial p1, p2,p3;
cout<<"Enter first polynomial :\n"<<endl;
p1.readPoly();
cout<<"\nThe first polynomial is:\n"<<endl;
p1.display();
cout<<endl;
cout<<"\nEnter second polynomial :\n"<<endl;
p2.readPoly();
cout<<"\nThe second polynomial is:\n"<<endl;
p2.display();
p3 = p1.add(p2);
cout<<endl;
cout<<"\nThe result is:\n"<<endl;
p3.display();
}
No comments:
Post a Comment