I am trying to create a Polynomial class .The terms of each object should be sorted for an ease of use( from higher exponent to smaller one). So i do the sorting in the addTerm
method but i am having some trouble doing it right. I either create an infinite linked list or the things are not sorted properly
#include <iostream>
using namespace std;
class Polynomial {
protected:
class Term {
public:
int exponent;
int coefficient;
Term *next;
Term(int exp, int coeff, Term *n) {
exponent = exp;
coefficient = coeff;
next = n;
}
friend class Polynomial;
};
public:
Polynomial() {
root = NULL;
}
Polynomial(const Polynomial &p) {
root = p.root;
}
~Polynomial() {
root = NULL;
}
void addTerm(int expon, int coeff) {
Term *prev = root;
Term *target = root;
if (root == NULL) {
Term tmp = Term(expon, coeff, NULL);
Term *p = &tmp;
root = p;
return;
}
while (target!= NULL && target->exponent < expon) {
prev = target;
target = target->next;
}
if (prev == target){
Term tmp = Term(expon, coeff, target;
Term *p = &tmp;
prev->next = p;
}else{
Term tmp = Term(expon, coeff, target);
Term *p = &tmp;
prev->next = p;
}
}
private:
Term *root;
};
int main() {
Polynomial q;
q.addTerm(1, 4);
q.addTerm(2, 3);
q.addTerm(3, 4);
//q.addTerm(1, 4);
//q.addTerm(2, 4);
// q.addTerm(2,4);
//q.print();
//cout << q;
}