-
Notifications
You must be signed in to change notification settings - Fork 0
/
polynomial.cpp
119 lines (90 loc) · 2.2 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
//Nick Scalzi
#include "polynomial.h"
#include "conversions.h"
polynomial::polynomial()
{
}
void polynomial::addTerm(int c, int e )
{
node* p = n; //pointer
node* q = 0; //pointer to previous element
if (c==0) return; //don't add the term if its coefficient is zero
if (n==0) //if this is the first term
{
n = new node(c,e);
return;
}
else
{
while(e<p->getExponent() &&p->next!=0) //cycle through the polynomial until either we discover
{
q=p;
p=p->next;
}
if(e==p->getExponent()) //if this exponent already exists
{
p->setCoefficient(p->getCoefficient()+c); //add the coefficients
return;
}
else if(e>p->getExponent())
{
p = new node(c,e,p);
if(q!=0) q->next = p; //if we're not at the front of the list, make sure the term before p, points to p.
else n=p; //if we're at the front of the list, make n point to p, the new first term.
return;
}
else
{
p->next = new node(c,e);
return;
}
}
}
std::string polynomial::print()
{
node* p =n;
std::string s="";
if (n==0) return "0"; //if the polynomial is empty, return 0
while(p!=0)
{
s+= intToString(p->getCoefficient());
s+="x^";
s+=intToString(p->getExponent());
if(p->next!=0)s+=" + ";
p=p->next;
}
return s;
}
polynomial& polynomial::operator=(polynomial rhs)
{
node* p=rhs.n;
n = 0; //reset the polynomial linked list
while(p!=0)
{
addTerm(p->getCoefficient(),p->getExponent()); //iteratively add the nodes from the rhs polynomial
p=p->next;
}
return *this;
}
polynomial& polynomial::operator+(polynomial rhs)
{
node* p=rhs.n;
polynomial r = *this;
while(p!=0)
{
r.addTerm(p->getCoefficient(),p->getExponent());
p=p->next;
}
return r;
}
polynomial& polynomial::operator-(polynomial rhs)
{
node* p=rhs.n;
polynomial r = *this;
while(p!=0)
{
r.addTerm(-1*(p->getCoefficient()),p->getExponent());
p=p->next;
}
return r;
}