I need to add two polynomials, which is composed of two ints. For example, the coefficient and the exponent 3x^2 would be constructed using 3 and 2 as parameters. I am getting a NullPointerException but I can't figure out why. Any help would be appreciated!
public class Polynomial {
private Node poly;
public Polynomial() {
}
private Polynomial(Node p) {
poly = p;
}
private class Term {
int coefficient;
int exponent;
private Term(int coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
}
}
private class Node {
private Term data;
private Node next;
private Node(Term data, Node next) {
this.data = data;
this.next = next;
}
}
public void addTerm(int coeff, int exp) {
Node pointer = poly;
if (pointer.next == null) {
poly.next = new Node(new Term(coeff, exp), null);
} else {
while (pointer.next != null) {
if (pointer.next.data.exponent < exp) {
Node temp = new Node(new Term(coeff, exp), pointer.next.next);
pointer.next = temp;
return;
}
pointer = pointer.next;
}
pointer.next = new Node(new Term(coeff, exp), null);
}
}
public Polynomial polyAdd(Polynomial p) {
return new Polynomial(polyAdd(this.poly, p.poly));
}
private Node polyAdd(Node p1, Node p2) {
if (p1 == p2) {
Term adding = new Term(p1.data.coefficient + p2.data.coefficient,
p1.data.exponent);
p1 = p1.next;
p2 = p2.next;
return new Node(adding, null);
}
if (p1.data.exponent > p2.data.exponent) {
p2 = p2.next;
}
if (p1.data.exponent < p2.data.exponent) {
p1 = p1.next;
}
if (p1.next != null && p2.next != null) {
return polyAdd(p1, p2);
}
return new Node(null, null);
}
}