-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpolynomial.cpp
143 lines (139 loc) · 2.83 KB
/
polynomial.cpp
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include<iostream>
using namespace std;
class Node{
public:
int cof;
int exp;
Node* next;
Node(int cof,int exp){
this->cof=cof;
this->exp=exp;
this->next=NULL;
}
};
class SLL{
public:
Node* head;
SLL(){
head=NULL;
}
bool isEmpty(){
return(head==NULL);
}
void insert(int ele,int exp){
Node* ptr=new Node(ele,exp);
if(isEmpty()){
head=ptr;
return;
}else{
Node* temp=head;
Node* temp2=NULL;
if(temp->exp<exp){
ptr->next=temp;
head=ptr;
return;
}
while(temp->next!=NULL && temp->next->exp>exp){
temp=temp->next;
}
temp2=temp->next;
temp->next=ptr;
ptr->next=temp2;
}
}
void display(){
if(!isEmpty()){
Node* temp=head;
cout<<temp->cof<<" x^"<<temp->exp;
temp=temp->next;
while(temp!=NULL){
if(temp->cof>0){
cout<<" + "<<temp->cof<<" x^"<<temp->exp;
}else if(temp->cof<0){
cout<<" "<<temp->cof<<" x^"<<temp->exp;
}
temp=temp->next;
}
cout<<endl;
}
}
SLL operator +(SLL poly1){
Node* ptr1=head;
Node* ptr2=poly1.head;
SLL result;
while(ptr1!=NULL && ptr2!=NULL){
if(ptr1->exp==ptr2->exp){
result.insert(ptr1->cof+ptr2->cof,ptr1->exp);
ptr1=ptr1->next;
ptr2=ptr2->next;
}
else if((ptr1->exp)>(ptr2->exp)){
result.insert(ptr1->cof,ptr1->exp);
ptr1=ptr1->next;
}else{
result.insert(ptr2->cof,ptr2->exp);
ptr2=ptr2->next;
}
}
while(ptr1!=NULL){
result.insert(ptr1->cof,ptr1->exp);
ptr1=ptr1->next;
}
while(ptr2!=NULL){
result.insert(ptr2->cof,ptr2->exp);
ptr2=ptr2->next;
}
return result;
}
SLL operator *(SLL poly2){
Node* ptr1=head;
Node* ptr2=poly2.head;
SLL result;
while(ptr1!=NULL){
SLL result_temp;
while(ptr2!=NULL){
result_temp.insert(ptr1->cof*ptr2->cof,ptr1->exp+ptr2->exp);
ptr2=ptr2->next;
}
result=result+result_temp;
ptr1=ptr1->next;
ptr2=poly2.head;
}
return result;
}
};
int main(){
SLL list1;
SLL list2;
SLL list3;
int count1,count2;
cout<<"Enter the number of terms in polynomial 1: ";
cin>>count1;
int i,ele,exp;
for(i=0;i<count1;i++){
cout<<"Enter the coefficient: ";
cin>>ele;
cout<<"Enter the power of x: ";
cin>>exp;
list1.insert(ele,exp);
}
cout<<"Enter the number of terms in polynomial 2: ";
cin>>count2;
for(i=0;i<count2;i++){
cout<<"Enter the coefficient: ";
cin>>ele;
cout<<"Enter the power of x: ";
cin>>exp;
list2.insert(ele,exp);
}
cout<<"Poly 1"<<endl;
list1.display();
cout<<"Poly 2"<<endl;
list2.display();
cout<<"Addition"<<endl;
list3=list1+list2;
list3.display();
cout<<"Multiplication"<<endl;
list3=list1*list2;
list3.display();
}