Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- struct Node{
- int pow;
- int coeff;
- Node* next;
- };
- class Poly{
- Node* head;
- public:
- Poly(){
- head=NULL;
- }
- void display(){
- Node *t = head;
- while(t!=NULL){
- cout<<t->coeff<<"x^"<<t->pow<< " + ";
- t = t->next;
- }
- }
- void insertAtEnd(int p,int c){
- Node* nn = new Node();
- nn->pow=p;
- nn->coeff = c;
- nn->next = NULL;
- if(head==NULL)
- head = nn;
- else{
- Node * t = head;
- while(t->next!=NULL)
- t = t->next;
- t->next = nn;
- }
- }
- void add(Poly* obj2, Poly* result){
- Node* t1 = this->head;
- Node* t2 = obj2->head;
- while(t1 && t2){
- if(t1->pow == t2->pow){
- result->insertAtEnd(t1->pow, (t1->coeff+t2->coeff));
- t1 = t1->next;
- t2 = t2->next;
- }
- else if(t1->pow > t2->pow){
- result->insertAtEnd(t1->pow, t1->coeff);
- t1 = t1->next;
- }
- else if(t2->pow > t1->pow){
- result->insertAtEnd(t2->pow, t2->coeff);
- t2 = t2->next;
- }
- }
- while(t1){
- result->insertAtEnd(t1->pow,t1->coeff);
- t1 = t1->next;
- }
- while(t2){
- result->insertAtEnd(t2->pow,t2->coeff);
- t2 = t2->next;
- }
- return;
- }
- };
- int main(){
- Poly obj1,obj2;
- Poly result;
- int n, coeff,pow;
- cout<<" How many terms in Poly 1? "<<endl;
- cin>>n;
- for(int i=0;i<n;i++){
- cin>>coeff;
- cin>>pow;
- obj1.insertAtEnd(pow,coeff);
- }
- cout<<" How many terms in Poly 2? "<<endl;
- cin>>n;
- for(int i=0;i<n;i++){
- cin>>coeff;
- cin>>pow;
- obj2.insertAtEnd(pow,coeff);
- }
- obj1.display();
- cout<<endl;
- obj2.display();
- cout<<endl;
- obj1.add(&obj2,&result);
- cout<<"Result "<<endl;
- result.display();
- cout<<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement