/** * Returns the polynomial obtained by multiplying the given polynomial p with this polynomial - * DOES NOT change this polynomial * * @param p Polynomial with which this polynomial is to be multiplied * @return A new polynomial which is the product of this polynomial and p. */ public Polynomial multiply(Polynomial p) { // If multiplying by zero, return the null list if (p.poly == null) return p; else if (this.poly == null) return this; Polynomial newList = new Polynomial(); // Nested loop to multiply terms. Multiplies first term by every term in second list and so on. for (Node list1 = this.poly; list1 != null; list1 = list1.next) { for (Node list2 = p.poly; list2 != null; list2 = list2.next) { Node n = new Node( list1.term.coeff * list2.term.coeff, list1.term.degree + list2.term.degree, null); newList.addToEnd(n); } } // sorts newList in ascending order and then combines like degrees. newList.sort(); newList.compress(); return newList; }