-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddPolynomial.cpp
More file actions
109 lines (103 loc) · 2.74 KB
/
addPolynomial.cpp
File metadata and controls
109 lines (103 loc) · 2.74 KB
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
//Write a program to represent a polynomial using
//linkedlist and add two polynomials
#include<bits/stdc++.h>
using namespace std;
struct node{
int coef;
int expo;
struct node* next;
};
struct node* insert(struct node* *head, int coef,int expo){
struct node* ptr=*head;
struct node* temp=new node();
temp->coef=coef;
temp->expo=expo;
temp->next=NULL;
if(*head==NULL){
*head=temp;
}else{
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=temp;
}
return *head;
}
struct node* addPoly(struct node* head1 , struct node* head2){
struct node* head3=NULL;
struct node* ptr1=head1;
struct node* ptr2=head2;
int co,exo;
while(ptr1!=NULL && ptr2!=NULL){
if(ptr1->expo == ptr2->expo){
co=ptr1->coef+ptr2->coef;
exo=ptr1->expo;
head3=insert(&head3,co,exo);
ptr1=ptr1->next;
ptr2=ptr2->next;
}else if( ptr1->expo > ptr2->expo){
co=ptr1->coef;
exo=ptr1->expo;
head3=insert(&head3,co,exo);
ptr1=ptr1->next;
}else{
co=ptr2->coef;
exo=ptr2->expo;
head3=insert(&head3,co,exo);
ptr2=ptr2->next;
}
}
while(ptr1 != NULL){
co=ptr1->coef;
exo=ptr1->expo;
head3=insert(&head3,co,exo);
ptr1=ptr1->next;
}
while(ptr2 !=NULL){
co=ptr2->coef;
exo=ptr2->expo;
head3=insert(&head3,co,exo);
ptr2=ptr2->next;
}
return head3;
}
void Display(struct node* head){
struct node* ptr = head;
while(ptr != NULL){
cout << ptr->coef << "x^(" << ptr->expo << ")";
if(ptr->next != NULL)
cout << " + ";
ptr = ptr->next;
}
cout << endl;
}
int main(){
struct node* ptr1=NULL;
struct node* ptr2=NULL;
int n1,n2;
int co,expo;
cout<<"Enter number of cooficient in first polynomial:";
cin>>n1;
cout<<"Enter Value of first Polynomial:"<<endl;
for(int i=0;i<n1;i++){
cout<<"Enter value of coeficient:";
cin>>co;
cout<<"Enter Value of exponent:";
cin>>expo;
ptr1=insert(&ptr1,co,expo);
}
cout<<"Enter number of cooficient in second polynomial:";
cin>>n2;
cout<<"Enter Value of second Polynomial:"<<endl;
for(int i=0;i<n2;i++){
cout<<"Enter value of coeficient:";
cin>>co;
cout<<"Enter Value of exponent:";
cin>>expo;
ptr2=insert(&ptr2,co,expo);
}
struct node* result=addPoly(ptr1, ptr2);
cout<<"Result:";
Display(result);
return 0;
}