linked list polynomial in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

linked list polynomial in java

I am trying to make a polynomial of linked list with add, multiply and print polynomial methods ....>unfortunately add method does not work with me package polynomialtester; import java.util.LinkedList; /** * * */ public class Polynomial { private Term poly = new Term(0,0); private Term last = poly; private class Term{ float coef; int pow; Term next; public Object data; Term (float c , int p) { coef = c; pow = p; } } public Polynomial(){} public Polynomial(float c , int p) { last.next = new Term(c,p); last = last.next; } public void add(Polynomial t) { Term newT = new Term(); newT.data = t; newT.next = first; first = newT; } public Polynomial multiply(Polynomial p) { Term p1 = this.poly; Term p2 = p.poly ; Term t = null; Term prod = null; Polynomial product = new Polynomial(); while (p1 != null){ while (p2 != null){ t = new Term(p1.coef * p2.coef ,p1.pow * p2.pow); p2 = p2.next; prod = add(t); } p1 = p1.next; p2 = p.poly; } product.poly = prod; return product; } public void print() { while (poly.next != null) { if (poly.coef == 0) System.out.println(poly.coef); else if (poly.coef == 1) System.out.println(poly.coef + "x"); else System.out.println(poly.coef + "x^" + poly.pow); poly = poly.next; } } }

11th May 2019, 2:26 PM
Student
Student  - avatar
1 Answer
+ 2
Much faster: Arrays. As your Index is equal to the power of your variable, you'll get, asuming x^4+3x^2+4, an array = [4, 0, 3, 0, 1]. Now ADD(polynom) is a simple vector operation.
11th May 2019, 7:34 PM
Daniel Adam
Daniel Adam - avatar