Data Structure and Algorithms
package array; public class Polynomial { class Term { int coef = 0; int degree = 0; Term next; Term(int c, int d) { coef = c; degree = d; next = null; } } private Term first; public Polynomial() { first = null; } //maintain the polynomial in descending order public void addTerm(int c, int d) { Term n = new Term(c, d); if (first == null ) { // n is the first term first = n; } else { Term cur = first; if(d>cur.degree) { // the degree of n is greater than that of the first term n.next = cur; first = n; return; } else { while(cur != null && cur.degree > d) { if(cur.next != null ) { if(cur.next.degree > d) { cur = cur.next; } else { n.next = cur.next; cur.next = n; return; } } else { // reach the last term cur.next = n; return; } } } } } public void print(){ Term cur = first; while ( cur != null ) { System.out.println( cur.coef + " " + cur.degree); cur = cur.next; } } //This method takes a polynomial as an input //return: a polynomial that is the sum of current polynomial and the input polynomial //For example, assume the current polynomial is 10x^20 - 9x^7 + 3 and the input polynomial is // 12x^16 + 6x^7 - 20x^2 - 2 // then the returned polynomial must be 10x^20 - 3x^7 -20x^2 +1 public Polynomial addPolynomial(Polynomial p) { //add your code here Polynomial result = null; return result; } public static void main(String[] arg) { Polynomial p = new Polynomial(); p.addTerm(2, 3); p.addTerm(3, 1); p.addTerm(4, 6); p.addTerm(1, 4); p.addTerm(1, 2); p.addTerm(1, 5); p.addTerm(-1, 0); p.addTerm(1, 100); p.print(); } }