Question: JAVA Data structures assignment. Need to change this linked-list polynomial into a MAP polynomial, using Map for the coefficients. Thank you! Following is the code:

JAVA Data structures assignment. Need to change this linked-list polynomial into a MAP polynomial, using Map for the coefficients. Thank you!

Following is the code:

import java.util.Iterator;

import java.util.LinkedList;

import java.util.ListIterator;

public class Polynomial {

LinkedList terms;

public static void main(String[] args) { Polynomial p = new Polynomial(new Term(-10, 0)); p.print(); p.add(new Polynomial(new Term(-1, 1))); p.print(); p.add(new Polynomial(new Term(9, 7))); p.print(); p.add(new Polynomial(new Term(5, 10))); p.print(); Polynomial q = p.multiply(p); q.print(); }

public Polynomial() { terms = new LinkedList<>(); }

public Polynomial(Term t) { terms = new LinkedList<>(); terms.add(t); }

public void add(Polynomial p) { int t = 0; boolean added; Term current; for (Term newTerm : p.terms) { added = false; while (!added && t < terms.size()) current = terms.get(t); if (current.getPower() == newTerm.getPower()) { current.addIfSamePower(newTerm); added = true; } else if (newTerm.getPower() > current.getPower()) { terms.add(t, new Term(newTerm.getCoefficient(), newTerm.getPower())); added = true; } t++; } if (!added) { terms.add(new Term(newTerm.getCoefficient(), newTerm.getPower())); //add to end } }

}

public Polynomial multiply(Polynomial p) Polynomial ans = new Polynomial(); for (Term t1 : p.terms) { for (Term t2 : terms) { Term t3 = t1.multiply(t2); ans.add(new Polynomial(t3)); } }

return ans; }

protected void print() { String s = ""; for (int i = 0; i < terms.size(); i++) { Term t = terms.get(i); if (t.getCoefficient() > 0) { if (i != 0) { s += " + "; } } else { s += " - "; } s += t.toString(); } System.out.print(s); System.out.println(); } }

public class Term { private double coefficient; private int power;

public Term(double coefficient, int power) { this.coefficient = coefficient; this.power = power; }

public double getCoefficient() { return coefficient; }

public int getPower() { return power; }

public Term multiply(Term t) { return new Term(coefficient * t.coefficient, power + t.power); }

public void addIfSamePower(Term t) { if (t.power == power) { coefficient += t.coefficient; } }

@Override public String toString() { if (power == 0) { return Math.abs(coefficient) + ""; } else if (power == 1) { return Math.abs(coefficient) + "x"; } else { return Math.abs(coefficient) + "x^" + power; } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!