I need to add two polynomials together using a recursive method.
This is for a past-due assignment (I imagine a similar thing will be on a test).
Main class:
public class Polynomial {
private Node poly;
public Polynomial(){
poly = new Node();
}
private Polynomial(Node node){
poly = node;
}
public void addTerm(int coef, int exp){
Term term = new Term(coef, exp);
Node node = new Node(term, null);
Node iterator = poly;
//if the list is empty just add the node
if (poly.next == null){
System.out.println("poly.next is null. adding node to first pos.");
poly.next = node;
return;
}
//if list isn't empty find the appropriate spot for it
while (iterator.next != null){
System.out.println("iterator.next != null...");
if (exp < iterator.next.data.exp){
System.out.println("\texp < iterator.next.data.exp");
node.next = iterator.next;
iterator.next = node;
return;
}
if (exp == iterator.next.data.exp){
System.out.println("\texp == iterator.next.data.exp");
iterator.next.data.coef += coef;
return;
}
iterator = iterator.next;
}
//if we get to this point then the list isn't empty
//and it doesn't fit inside the list, hence it must
//be added to the end of the list
System.out.println("list wasn't empty, didn't fit inside");
iterator.next = node;
return;
}
#Override
public String toString(){
Node iterator = poly;
String out = "";
if (poly.next == null){
return out;
}
while(iterator.next != null){
out += iterator.next.data.coef;
out += "*x^";
out += iterator.next.data.exp;
out += " + ";
iterator = iterator.next;
}
return out.substring(0, out.lastIndexOf('+'));
}
public Polynomial addPolynomial (Polynomial that){
Polynomial ret = new Polynomial();
Polynomial iterator = this;
return addPolynomial(that, ret, iterator);
}
public Polynomial addPolynomial(Polynomial that, Polynomial ret, Polynomial iterator){
if (iterator.poly.next == null){
return new Polynomial(that.poly);
}
if (that.poly.next == null){
return new Polynomial(iterator.poly);
}
if (iterator.poly.next.data.exp < that.poly.next.data.exp){
ret.addTerm(iterator.poly.next.data.coef, iterator.poly.next.data.exp);
iterator.poly = iterator.poly.next;
return iterator.addPolynomial(that);
}
if (iterator.poly.next.data.exp == that.poly.next.data.exp){
ret.addTerm(iterator.poly.next.data.coef + that.poly.next.data.coef, iterator.poly.next.data.exp);
iterator.poly = iterator.poly.next;
that.poly = that.poly.next;
return iterator.addPolynomial(that);
}
if (iterator.poly.next.data.exp > that.poly.next.data.exp){
ret.addTerm(that.poly.next.data.coef, that.poly.next.data.exp);
that.poly = that.poly.next;
return iterator.addPolynomial(that);
}
return ret;
}
/*
* Term
*/
private class Term implements Comparable{
int coef;
int exp;
public int getCoef() {
return coef;
}
public void setCoef(int coef) {
this.coef = coef;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public Term(int coef, int exp) {
this.coef = coef;
this.exp = exp;
}
public int compareTo(Object rhs){
Term that = (Term)rhs;
return this.exp - that.exp;
}
}//end Term
/*
* Node
*/
private class Node{
Term data;
Node next;
public Term getData() {
return data;
}
public void setData(Term data) {
this.data = data;
this.next = null;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node() {
this.data = null;
this.next = null;
}
public Node(Term data, Node next) {
this.data = data;
this.next = next;
}
}//end Node
}
Test Class:
public class Polynomials {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Polynomial p1 = new Polynomial();
Polynomial p2 = new Polynomial();
Polynomial p0 = new Polynomial();
p1.addTerm(1, 2);
p1.addTerm(1, 4);
p1.addTerm(1, 6);
p2.addTerm(1, 1);
p2.addTerm(1, 3);
p2.addTerm(1, 5);
System.out.println("p1 = " + p1.toString());
System.out.println("p2 = " + p2.toString());
System.out.println("Adding p1 to p2...");
p0 = p1.addPolynomial(p2);
System.out.println(p0.toString());
}
}
Have you considered this way of doing it?
public class Polynomial {
public static void main(String[] args) {
Polynomial p1 = new Polynomial();
Polynomial p2 = new Polynomial();
Polynomial p0 = new Polynomial();
p1.addTerm(1, 2);
p1.addTerm(1, 4);
p1.addTerm(1, 6);
p2.addTerm(1, 1);
p2.addTerm(2, 3);
p2.addTerm(2, 2);
p2.addTerm(1, 5);
System.out.println("p1 = " + p1.toString());
System.out.println("p2 = " + p2.toString());
System.out.println("Adding p1 to p2...");
p0 = p1.addPolynomial(p2);
System.out.println(p0.toString());
for(int i = 0;i < 100;i++) {
p1 = new Polynomial();
p2 = new Polynomial();
for(int j = 0;j < 4;j++) {
p1.addTerm((int) (10 * Math.random()) - 5,
(int) (4 * Math.random()));
p2.addTerm((int) (10 * Math.random()) - 5,
(int) (4 * Math.random()));
}
p0 = p1.addPolynomial(p2);
System.out.println(p1 + "\n" + p2 + "\n" + p0 + "\n");
}
}
enum Comp {
LT, EQ, GT
}
static Comp cmp(int a, int b) {
return (a < b) ? Comp.LT : (a == b) ? Comp.EQ : Comp.GT;
}
private Term poly;
public Polynomial() {
poly = null;
}
public void addTerm(int coef, int exp) {
if (coef == 0) return;
Term term = new Term(coef, exp,null);
if (poly == null) {
poly = term;
} else {
poly = poly.add(term);
}
}
#Override
public String toString() {
if (poly == null) return "0";
StringBuilder buf = new StringBuilder();
poly.writeTo(buf);
return buf.toString();
}
public Polynomial addPolynomial(Polynomial that) {
Polynomial ret = new Polynomial();
if (poly != null) {
ret.poly = new Term(poly);
if (that.poly != null) {
ret.poly = ret.poly.add(new Term(that.poly));
}
} else if (that.poly != null) {
ret.poly = new Term(that.poly);
}
return ret;
}
private class Term {
final int coef;
final int exp;
final Term next;
Term(int coef, int exp, Term next) {
this.coef = coef;
this.exp = exp;
this.next = next;
}
Term(Term copy) {
this.coef = copy.coef;
this.exp = copy.exp;
if (copy.next == null) {
this.next = null;
} else {
this.next = new Term(copy.next);
}
}
Term add(Term other) {
if (other == null) return this;
switch (cmp(this.exp, other.exp)) {
case LT: {
Term n = other.add(this);
return n;
}
case GT: {
if (next == null) {
return new Term(coef,exp,other);
}
return new Term(coef,exp,next.add(other));
}
default: {
Term n = (next==null) ? other.next : next.add(other.next);
int nc = coef+other.coef;
return (nc!=0) ? new Term(nc,exp,n) : n;
}
}
}
public void writeTo(StringBuilder app) {
if (coef != 1 || exp == 0) app.append(coef);
if (exp == 1) {
app.append("x");
} else if (exp != 0) {
app.append("x^").append(exp);
}
if (next != null) {
app.append('+');
next.writeTo(app);
}
}
}
}
Well that's certainly a bit more complex than necessary.
So you want to add a Polynomial to an already existing one, i.e.:
4*x^2 + 4 to 5*x^4+x+5, which results in: 5*x^4+4*x^2+x+9
You could obviously simplify the problem quite a bit by just using an array, but it's also not that hard with a linked list, the code should look something like this:
You have two pointers one pointing to the current position in the polynomial we want to add values (term1) and another one in the one we want to add (term2), both initialized to the lowest entry in the linked list (which we assume is sorted according to the exponent).
while term1 != NULL && term2 != NULL do:
term1 > term2:
add term2 to list
term2 = term2.next()
term2 > term1:
term1 = term1.next()
term1 = term2:
add term2 to term1
term1 = term1.next()
term2 = term2.next()
while term1 == NULL && term2 != NULL:
add term2
term2 = term2.next()
You can easily adapt that to also create a new polynomial instead of adding one to the other.
Okay so a little bit more details on how to turn the iterative solution into a recursive one:
The first thing you always have to do when thinking about recursion is your exit condition.
In this case if you think about that's easy: We only do work as long as term2 is not NULL, as soon as term2 is NULL we're finished.
The next step is thinking about a good method signature and that's also quite easy this time, since we only need the two terms, so you can just use the two iterators:
void addTogether(Iterator term1, Iterator term2); (assuming you're using an interface that's similar to the ListIterator, since you need to insert at the position before term1 - there are several ways to implement that)
ANd now you've just got to get rid of the while loops and replace them with a recursive call (in which you distinguish the different cases, do the necessary action and call it again)
Related
Could someone check my code for why I'm getting NullPointerExceptions in various methods? I've been racking my brain and can't figure out what is wrong.
I'm attempting to create a polynomial class that stores polynomials in a linked list using an inner class Terms. If you have any questions on the methods, please let me know!
public class Polynomial {
// Create the "Term" Inner Class for Handling the Respective Nodes for this Class
protected class Term {
int coefficient; // Coefficient of the Current Term
int exponent; // Exponent of the Current Term
Term next; // Reference to the Next Term in the Linked List (if Possible)
public Term (int coefficient, int exponent, Term next) { // General Constructor Method
this.coefficient = coefficient;
this.exponent = exponent;
this.next = next;
}
public Term (int coefficient, int exponent) { // No "Term next" (The Next Term Needs to be Null!)
this (coefficient, exponent, null);
}
public Term () { // Basic Constructor Method (No Input Necessary)
this (0, 0, null);
}
}
protected Term poly; // Starting Point (Dummy Header Node)
public Polynomial() { // General Constructor Method
poly = new Term();
clear();
}
public Polynomial(int [] terms) { // Constructor Method (Using an Integer Array of Coefficients and Exponents)
if (!(terms.length % 2 == 0)) { // This Array MUST Possess an Even, Positive Number of Elements (Alternating Coefficients and Corresponding Exponents)
throw new IllegalArgumentException("Your array must have an even, positive number of elements for use in our program. Thanks!");
}
else { // Proceed Normally...
poly = new Term(); // Dummy Header Node
clear();
setTerms(terms);
}
}
// Create the clear() Method for Promptly Resetting the Polynomial Back to 0
public void clear() {
poly.next = null;
}
// Create the setTerms(int [] terms) Method for Setting the Polynomial to the Appropriate Set of Terms
public void setTerms(int [] terms) {
Term temp = poly;
for (int i = 0; i < terms.length; i = i + 2) { // Incrementing By 2 (Each Polynomial Necessitates a Coefficient & Exponent, or Lack Thereof)
if (terms[i + 1] < 0) { // Polynomials CANNOT Have Coefficients with Negative Exponents
throw new IllegalArgumentException("Coefficients in polynomials must have positive exponents for use in our program. Thanks!");
}
temp.next = new Term(terms[i], terms[i + 1]);
temp = temp.next;
}
}
// Create the toString() for Outputting the Polynomial to the User's Screen
public String toString() {
String polynomialString = "";
boolean firstTerm = true;
if (poly.next == null) {
return "0"; // The ONLY Time 0 is Outputted as a Coefficient is if the Polynomial = 0
}
while (poly.next != null) { // Reached the Conclusion of the Linked List?
if (poly.next.coefficient > 0) { // Checking for Positivity
if (!firstTerm) { // First Term DOESN'T Need a "+" Sign
polynomialString = polynomialString + "+";
}
}
if (poly.next.coefficient == 1) {
if (poly.next.exponent == 1) {
polynomialString = polynomialString + "x"; // Print ONLY the Variable (x)
}
else {
polynomialString = polynomialString + "x^" + poly.next.exponent; // Otherwise, Print "x^exponent"
}
}
else if (poly.next.coefficient == -1) {
if (poly.next.exponent == 1) {
polynomialString = polynomialString + "-x"; // Print ONLY the Variable (x)
}
else {
polynomialString = polynomialString + "-x^" + poly.next.exponent; // Otherwise, Print "x^exponent"
}
}
else if (poly.next.exponent == 1) {
polynomialString = polynomialString + poly.next.coefficient + "x"; // Print "coefficientx"
}
else if (poly.next.exponent == 0) { // Print the Coefficient Alone...
polynomialString = polynomialString + poly.next.coefficient;
}
else { // Proceed Normally (WITH Coefficient & Exponent)
polynomialString = polynomialString + poly.next.coefficient + "x^" + poly.next.exponent;
}
poly = poly.next;
firstTerm = false;
}
return polynomialString;
}
// Create the addTerm() Method that Incorporates the Term "Coefficient * x^Exponent" to the Respective Polynomial (Needs Help)
public void addTerm(int coefficient, int exponent) {
if (exponent < 0) { // Polynomials CANNOT Have Coefficients with Negative Exponents
throw new IllegalArgumentException("Coefficients in polynomials must have positive exponents for use in our program. Thanks!");
}
Term newTerm = new Term(coefficient, exponent);
Term p = poly;
while (p.next != null && p.next.exponent > exponent) {
p = p.next;
}
newTerm.next = p.next;
p.next = newTerm;
}
// Create the eval() Method that Returns the Result of Evaluating the Polynomial at x = val (USE Horner's Method for this Method)
public double eval(double val) {
double result = 0;
Term p = poly;
p = p.next;
result += p.coefficient * val + p.next.coefficient;
p = p.next;
while (p.next != null) {
result = result * val + p.next.coefficient;
p = p.next;
}
return result;
}
// Create the multiply() Method that Returns a NEW Polynomial After Multiplying Each Term by the scalar Variable
public Polynomial multiply(int scalar) {
Polynomial newPoly = new Polynomial();
Term p = poly.next;
while (p.next != null) {
newPoly.addTerm(scalar * p.coefficient, p.exponent); // Multiplying the Coefficients and Scalar Together
p = p.next;
}
return newPoly;
}
// Create the add(Polynomial rhs) Method that Returns the Result of ADDING the "rhs" polynomial to "this" polynomial
public Polynomial add(Polynomial rhs) {
Polynomial newPoly = new Polynomial();
Term p1 = poly.next; // this polynomial
Term p2 = rhs.poly.next; // rhs polynomial
while (p1.next != null && p2.next != null) {
if (p1.exponent == p2.exponent) { // Same Exponents?
newPoly.addTerm(p1.coefficient + p2.coefficient, p1.exponent);
p1 = p1.next;
p2 = p2.next;
}
else if (p1.exponent > p2.exponent) { // Greater than rhs Polynomial?
newPoly.addTerm(p1.coefficient, p1.exponent);
p1 = p1.next;
}
else { // Less than rhs Polynomial?
newPoly.addTerm(p2.coefficient, p2.exponent);
p2 = p2.next;
}
}
if (p1.next == null) {
while (p2.next != null) { // Does the rhs Polynomial have Extra Terms?
newPoly.addTerm(p2.coefficient, p2.exponent);
p2 = p2.next;
}
}
if (p2.next == null) {
while (p1.next != null) { // Does the this Polynomial have Extra Terms?
newPoly.addTerm(p1.coefficient, p1.exponent);
p1 = p1.next;
}
}
return newPoly;
}
// Create the multiply(Polynomial rhs) Method that Returns the Result of MULTIPLYING the "rhs" polynomial to "this" polynomial
public Polynomial multiply(Polynomial rhs) {
Polynomial newPoly = new Polynomial();
Term p1 = poly.next; // this polynomial
Term p2 = rhs.poly.next; // rhs polynomial
while (p1.next != null) {
while (p2.next != null) {
newPoly.addTerm(p1.coefficient * p2.coefficient, p1.exponent + p2.exponent);
p2 = p2.next;
}
p1 = p1.next;
}
return newPoly;
}
I have an assignment for my Data Structures class. In the assignment, we have to implement polynomial addition using linked lists. I think I have it down but eclipse is giving me a null pointer exception. My problem is with the add method, though I included the whole class for context. Multiply I will tackle after.. Please help.
class PolynomialLinkedList{
private static class PNode{
private int coe;
private int exp;
private PNode next;
public PNode(int c, int e){
this(c, e, null);
}
public PNode(int c, int e, PNode n){
coe = c;
exp = e;
next = n;
}
public void setCoe(int c){ coe = c;}
public void setExp(int e){ exp = e;}
public void setNext(PNode n){ next = n;}
public int getCoe(){ return coe;}
public int getExp(){ return exp;}
public PNode getNext(){ return next;}
}
private PNode first;
private PNode last;
public PolynomialLinkedList(){
first = last = null;
}
public PolynomialLinkedList(int c, int e){
PNode tempn = new PNode(c, e);
first = last = tempn;
}
public void print(){
if (first == null){
System.out.println();
return;
}
PNode temp = first;
String ans = "";
while (temp != null){
if (temp.getCoe() > 0) {
if (temp != first) ans = ans + " + ";
ans = ans + temp.getCoe();
}
else if (temp.getCoe() < 0) ans = ans + " - " + temp.getCoe() * -1;
if (temp.getExp() != 0){
ans = ans + "X^" + temp.getExp();
}
temp = temp.getNext();
}
System.out.println(ans);
}
public PolynomialLinkedList add(PolynomialLinkedList s){
PolynomialLinkedList sum = new PolynomialLinkedList();
PNode temp1 = this.first;
PNode temp2 = s.first;
PNode tempAns = new PNode(0,0);
if(temp1.exp != temp2.exp) {
while(temp1.exp > temp2.exp) {
tempAns.setCoe(temp1.coe);
tempAns.setExp(temp1.exp);
temp1 = temp1.getNext();
tempAns = sum.first.getNext();
}
while(temp1.exp < temp2.exp) {
tempAns.setCoe(temp2.coe);
tempAns.setExp(temp2.exp);
temp2 = temp2.getNext();
tempAns = sum.first.getNext();
}
}
else if(temp1.exp == temp2.exp) {
while(temp1.exp == temp2.exp) {
tempAns.setCoe((temp1.coe + temp2.coe));
tempAns.setExp(temp1.exp);
temp1 = temp1.getNext();
temp2 = temp2.getNext();
tempAns = sum.first.getNext();
}
}
return sum;
}
public PolynomialLinkedList multiply(PolynomialLinkedList s){
PolynomialLinkedList product = new PolynomialLinkedList();
//implement this method
return product;
}
}
I'm stuck on this problem:
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
The problem is that my result is 8 8 while the result should be 8 0 8.
I printed out the sum and it is 8 10 8 so it should work.
Any ideas?
Here is my code:
public Node addNumbers(Node number1, Node number2) {
if(number1 == null && number2 == null)
return null;
Node sumOf = null;
int sum = 0;
int carry = 0;
while(number1 != null && number2 != null) {
sum = number1.data + number2.data + carry;
System.out.println(sum);
// update carry for next operation
if(sum > 9)
carry = 1;
else
carry = 0;
if(sum > 9) {
if(sumOf == null) {
sumOf = new Node(sum % 10);
} else {
sumOf.next = new Node(sum % 10);
}
} else {
if(sumOf == null) {
sumOf = new Node(sum);
} else {
sumOf.next = new Node(sum);
}
}
number1 = number1.next;
number2 = number2.next;
}
return sumOf;
}
public void toString(Node node) {
System.out.println();
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
AddTwoNumbers add = new AddTwoNumbers();
number1 = new Node(3);
number1.next = new Node(1);
number1.next.next = new Node(5);
number2 = new Node(5);
number2.next = new Node(9);
number2.next.next = new Node(2);
System.out.println("numbers: ");
add.toString(number1);
add.toString(number2);
System.out.println();
System.out.println("after adding: ");
add.toString(add.addNumbers(number1, number2));
}
}
You only ever set sumOf (if it is null) and sumOf.next (if sumOf is not null). Your resulting list therefore never has more than two elements. You need to track the current tail of your list and append there, instead of always appending to sumOf.
Additionally, you need to handle the cases where one input number has more digits than the other, and where you have non-zero carry after exhausting all the input digits. You do not presently handle either.
Here is the solution, do note that i carry forward when the sum of two integers is greater than 9 else i continue with the sum of next integers from both the list.
class Node {
private Object data;
private Node next;
public Object getData() { return data; }
public void setData(Object data) { this.data = data; }
public Node getNext() { return next; }
public void setNext(Node next) { this.next = next; }
public Node(final Object data, final Node next) {
this.data = data;
this.next = next;
}
#Override
public String toString() { return "Node:[Data=" + data + "]"; }
}
class SinglyLinkedList {
Node start;
public SinglyLinkedList() { start = null; }
public void addFront(final Object data) {
// create a reference to the start node with new data
Node node = new Node(data, start);
// assign our start to a new node
start = node;
}
public void addRear(final Object data) {
Node node = new Node(data, null);
Node current = start;
if (current != null) {
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(node);
} else {
addFront(data);
}
}
public void deleteNode(final Object data) {
Node previous = start;
if (previous == null) {
return;
}
Node current = previous.getNext();
if (previous != null && previous.getData().equals(data)) {
start = previous.getNext();
previous = current;
current = previous.getNext();
return;
}
while (current != null) {
if (current.getData().equals(data)) {
previous.setNext(current.getNext());
current = previous.getNext();
} else {
previous = previous.getNext();
current = previous.getNext();
}
}
}
public Object getFront() {
if (start != null) {
return start.getData();
} else {
return null;
}
}
public void print() {
Node current = start;
if (current == null) {
System.out.println("SingleLinkedList is Empty");
}
while (current != null) {
System.out.print(current);
current = current.getNext();
if (current != null) {
System.out.print(", ");
}
}
}
public int size() {
int size = 0;
Node current = start;
while (current != null) {
current = current.getNext();
size++;
}
return size;
}
public Node getStart() {
return this.start;
}
public Node getRear() {
Node current = start;
Node previous = current;
while (current != null) {
previous = current;
current = current.getNext();
}
return previous;
}
}
public class AddNumbersInSinglyLinkedList {
public static void main(String[] args) {
SinglyLinkedList listOne = new SinglyLinkedList();
SinglyLinkedList listTwo = new SinglyLinkedList();
listOne.addFront(5);
listOne.addFront(1);
listOne.addFront(3);
listOne.print();
System.out.println();
listTwo.addFront(2);
listTwo.addFront(9);
listTwo.addFront(5);
listTwo.print();
SinglyLinkedList listThree = add(listOne, listTwo);
System.out.println();
listThree.print();
}
private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
SinglyLinkedList result = new SinglyLinkedList();
Node startOne = listOne.getStart();
Node startTwo = listTwo.getStart();
int carry = 0;
while (startOne != null || startTwo != null) {
int one = 0;
int two = 0;
if (startOne != null) {
one = (Integer) startOne.getData();
startOne = startOne.getNext();
}
if (startTwo != null) {
two = (Integer) startTwo.getData();
startTwo = startTwo.getNext();
}
int sum = carry + one + two;
carry = 0;
if (sum > 9) {
carry = sum / 10;
result.addRear(sum % 10);
} else {
result.addRear(sum);
}
}
return result;
}
}
Sample Run
Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]
**#In Python:-**
class Node():
def __init__(self,value):
self.value=value
self.nextnode=None
class LinkedList():
def __init__(self):
self.head=None
def add_element(self,value):
node=Node(value)
if self.head is None:
self.head =node
return
crnt_node=self.head
while crnt_node.nextnode is not None:
crnt_node=crnt_node.nextnode
crnt_node.nextnode=node
def reverse_llist(self):
crnt_node=self.head
if crnt_node == None:
print('Empty Linkned List')
return
old_node = None
while crnt_node:
temp_node = crnt_node.nextnode
crnt_node.nextnode = old_node
old_node = crnt_node
crnt_node = temp_node
self.head = old_node
def converted_llist(self):
crnt_node=self.head
carry_value=0
while True:
#print(crnt_node.value)
if (crnt_node.value+1)%10==0:
carry_value=1
crnt_node.value=0
print(crnt_node.value,end='->')
else:
print(crnt_node.value+carry_value,end='->')
if crnt_node.nextnode is None:
break
crnt_node=crnt_node.nextnode
print('None')
def print_llist(self):
crnt_node=self.head
while True:
print(crnt_node.value,end='->')
if crnt_node.nextnode is None:
break
crnt_node=crnt_node.nextnode
print('None')
list_convert=LinkedList()
list_convert.add_element(1)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.reverse_llist()
list_convert.print_llist()
list_convert.converted_llist()
I have a question to complete using Java Polynomials. I've set up all my code and it looks to be ok but with my composite method I receive a different output than is expected.
class Polyonmial
{
final static private int mantissa=52;
final static private double epsilon=Math.pow(2.0,-mantissa);
private double coefficient=0.0;
private int power=0;
private Polynomial successor=null;
public Polynomial(double coefficient, int power)
{
if (Double.isNaN(coefficient)) return;
if (Math.abs(coefficient)<epsilon) return;
if (power<0) return;
this.coefficient=coefficient;
this.power=power;
}
final public double coefficient(int power)
{
if (power<0) return 0.0;
Polynomial traverser=this;
do
{
if (traverser.power<power) return 0.0;
if (traverser.power==power) return traverser.coefficient;
traverser=traverser.successor;
}
while (traverser!=null);
return 0.0;
}
final public Polynomial composite(Polynomial that)
{
if (that==null) return null;
Polynomial thisClone = this.clone();
Polynomial thatClone = that.clone();
Polynomial temp = new Polynomial(0.0,0);
Polynomial result = new Polynomial(0.0,0);
while(thisClone != null)
{
if (thisClone.power == 0)
{
temp.coefficient = 1.0;
temp.power = 0;
}
else
{
if (thisClone.power == 1)
temp = thatClone;
}
//System.out.println("temp:"+temp);
while(temp != null)
{
temp.coefficient = thisClone.coefficient*temp.coefficient;
result = result.plus(temp);
temp = temp.successor;
}
temp = new Polynomial(0.0,0);
thisClone=thisClone.successor;
}
return result;
}
final public Polynomial[] dividedBy(Polynomial that)
{
if (that==null) return null;
if (that.coefficient==0.0) return null;
Polynomial quotient=new Polynomial(0.0,0);
Polynomial remainder=this.clone();
Polynomial traverser = this.clone();
Polynomial resultoftemp = new Polynomial(0.0, 0);
Polynomial temp = new Polynomial(0.0, 0);
double thiscoffe = this.coefficient(this.degree());
double thatcoffe = that.coefficient(that.degree());
if(that.coefficient !=0 && that.power !=0)
{
quotient.coefficient = thatcoffe / thiscoffe;
quotient.power = that.power - this.power;
}
while(traverser !=null)
{
temp.power = quotient.power + traverser.power;
temp.coefficient = quotient.coefficient * traverser.coefficient;
traverser=traverser.successor;
resultoftemp = resultoftemp.plus(temp);
remainder = that.minus(resultoftemp);
}
Polynomial[] result=new Polynomial[2];
result[0]=quotient;
result[1]=remainder;
return result;
}
final public Polynomial integrate()
{
if (this.coefficient==0.0) return new Polynomial(0.0,0);
Polynomial result=this.clone();
Polynomial temp = new Polynomial(0.0, 0);
Polynomial rstemp = new Polynomial(0.0, 0);
while(result!=null)
{
rstemp.power = result.power + 1;
rstemp.coefficient = result.coefficient / (result.power +1);
result = result.successor;
temp = temp.plus(rstemp);
}
return result;
}
final public Polynomial minus(Polynomial that)
{
if (that==null) return null;
if (this.equals(that)) return new Polynomial(0.0,0);
Polynomial result=this.clone();
if (that.coefficient==0.0) return result;
Polynomial traverser=that;
do
{
add(result,-traverser.coefficient,traverser.power);
traverser=traverser.successor;
}
while (traverser!=null);
return result;
}
final public int powerMax()
{
int max=Integer.MIN_VALUE;
Polynomial traverser=this;
do
{
if (max<traverser.power) max=traverser.power;
traverser=traverser.successor;
}
while (traverser!=null);
return max;
}
final public int powerMin()
{
int min=Integer.MAX_VALUE;
Polynomial traverser=this;
do
{
if (min>traverser.power) min=traverser.power;
traverser=traverser.successor;
}
while (traverser!=null);
return min;
}
}
In my expected output file I am supposed to receive this:
(-1.0*X^1+1.0).composite(-1.0*X^1+1.0)=
1.0*X^1
But instead I receive:
(-1.0*X^1+1.0).composite(-1.0*X^1+1.0)=
1.0*X^1+1.0
Any tips or help is greatly appreciated.
I have slightly changed your composite method as so (logically equivalent, brace moves and println additions):
final public Polynomial composite(Polynomial that) {
if (that==null) return null;
Polynomial thisClone = this.clone();
Polynomial thatClone = that.clone();
Polynomial temp = new Polynomial(0.0,0);
Polynomial result = new Polynomial(0.0,0);
while(thisClone != null) {
System.out.println("composite with term degree: " + thisClone.power);
if (thisClone.power == 0) {
temp.coefficient = 1.0;
temp.power = 0;
} else if (thisClone.power == 1) {
temp = thatClone;
} else {
for(int i=2; i<=thisClone.power; i++) {
temp = temp.plus(thatClone.times(thatClone));
}
}
System.out.println("temp heading in: " + temp);
while(temp != null) {
temp.coefficient = thisClone.coefficient*temp.coefficient;
result = result.plus(temp);
temp = temp.successor;
}
System.out.println("result so far: " + result);
temp = new Polynomial(0.0,0);
thisClone=thisClone.successor;
}
return result;
}
and for the example (-1.0*X^1+1.0).composite(-1.0*X^1+1.0), this is the output:
composite with term degree: 1
temp heading in: -1.0*X^1+1.0
result so far: 1.0*X^1
composite with term degree: 0
temp heading in: 1.0
result so far: 1.0*X^1+1.0
Am I correct to believe that the first "result so far" should be "-1.0*X^1-1.0"?
If so, let's examine the loop:
while(temp != null) {
temp.coefficient = thisClone.coefficient*temp.coefficient;
result = result.plus(temp);
temp = temp.successor;
}
I think this is your problem: result = result.plus(temp) is adding not just the "current term" to temp, but also the successor term. But then you loop on temp by setting it equal to its successor and do it again!
I think the solution is something like this (first calculate all temp terms, then update result):
Polynomial looptemp = temp;
while(looptemp != null) {
looptemp.coefficient = thisClone.coefficient*looptemp.coefficient;
looptemp = looptemp.successor;
}
result = result.plus(temp);
At the very least, it works for the single example I tried.
I'm making a program that can recursively add Polynomials (represented by Linked Lists) together. But I keep getting a null pointer exception in the line if (p1.data.exp == p2.data.exp) {
I've tried debugging by setting both terms to either one or the other, but I keep getting the error (does this mean that they are both null?). I don't see how this can happen since it should return before getting to this part if they are null.
Does anyone have suggestions?
Main:
public class Polynomial {
private Node poly;
public Polynomial(){
poly = new Node();
}
private Polynomial(Node node){
poly = node;
}
public void addTerm(int coef, int exp){
Term term = new Term(coef, exp);
Node node = new Node(term, null);
Node iterator = poly;
//if the list is empty just add the node
if (poly.next == null){
System.out.println("poly.next is null. adding node to first pos.");
poly.next = node;
return;
}
//if list isn't empty find the appropriate spot for it
while (iterator.next != null){
System.out.println("iterator.next != null...");
if (exp < iterator.next.data.exp){
System.out.println("\texp < iterator.next.data.exp");
node.next = iterator.next;
iterator.next = node;
return;
}
if (exp == iterator.next.data.exp){
System.out.println("\texp == iterator.next.data.exp");
iterator.next.data.coef += coef;
return;
}
iterator = iterator.next;
}
//if we get to this point then the list isn't empty
//and it doesn't fit inside the list, hence it must
//be added to the end of the list
System.out.println("list wasn't empty, didn't fit inside");
iterator.next = node;
return;
}
#Override
public String toString(){
Node iterator = poly;
String out = "";
if (poly.next == null){
return out;
}
while(iterator.next != null){
out += iterator.next.data.coef;
out += "*x^";
out += iterator.next.data.exp;
out += " + ";
iterator = iterator.next;
}
return out.substring(0, out.lastIndexOf('+'));
}
public Polynomial addPolynomial (Polynomial that){
Polynomial ret = new Polynomial();
Polynomial iterator = this;
return new Polynomial(addPolys(this.poly, that.poly));
}
public Node addPolys(Node p1, Node p2) {
// If P1 is null, just use P2
if (p1 == null) {
p1 = p2;
p2 = null;
}
// if P1 is still null, no P2 either so finished
if (p1 == null) return null;
Node ret = new Node();
// if P2 is null now, just one poly remains
if (p2 == null) {
ret.data = p1.data;
p1 = p1.next;
} else {
// do we combine nodes?
if (p1.data.exp == p2.data.exp) {
ret.data = new Term(p1.data.coef + p2.data.coef, p1.data.exp
+ p2.data.exp);
p1 = p1.next;
p2 = p2.next;
} else {
// we just copy a node
// make p1 the bigger exponent
if (p1.data.exp < p2.data.exp) {
Node t = p1;
p1 = p2;
p2 = t;
}
ret.data = p1.data;
p1 = p1.next;
}
}
ret.next = addPolys(p1, p2);
return ret;
}
/*
* Term
*/
private class Term implements Comparable{
int coef;
int exp;
public int getCoef() {
return coef;
}
public void setCoef(int coef) {
this.coef = coef;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public Term(int coef, int exp) {
this.coef = coef;
this.exp = exp;
}
public int compareTo(Object rhs){
Term that = (Term)rhs;
return this.exp - that.exp;
}
}//end Term
/*
* Node
*/
private class Node{
Term data;
Node next;
public Term getData() {
return data;
}
public void setData(Term data) {
this.data = data;
this.next = null;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node() {
this.data = null;
this.next = null;
}
public Node(Term data, Node next) {
this.data = data;
this.next = next;
}
}//end Node
}
Test:
public class Polynomials {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Polynomial p1 = new Polynomial();
Polynomial p2 = new Polynomial();
Polynomial p0 = new Polynomial();
p1.addTerm(1, 2);
p1.addTerm(1, 4);
p1.addTerm(1, 6);
p2.addTerm(1, 1);
p2.addTerm(1, 3);
p2.addTerm(1, 5);
System.out.println("p1 = " + p1.toString());
System.out.println("p2 = " + p2.toString());
System.out.println("Adding p1 to p2...");
p0 = p1.addPolynomial(p2);
System.out.println(p0.toString());
}
}
One of the data fields in the Node object is not initialized. My guess is that this is setting the data to null.
Node node = new Node(term, null);
So any node variable that references that object will throw an exception when you do p1.data.exponent.
in this part
if (p1.data.exp == p2.data.exp)
property 'data' or 'exp' is null.
I'll give an advice write your code more protective:
use getter and setter method;
don't use chain of references (eg, p1.data.exp);
test 'null' case;
add log infromation;
bye
I'd guess that p1.data or p2.data is null, so you can't obtain the exponent from it.