Combining Like Terms/ LinkedList Polynomial [Java] - java

So my issue here is getting this program to combine like terms, I've tried about 3 different ways of going about this and cannot figure it out. I can sort the array in somewhat the correct order but not get it to combine.
public static Node multiply(Node poly1, Node poly2) {
Node polynomial1 = poly1;
Node polynomial2 = poly2;
Node mult = poly2;
Node temp3 = null;
float cmb = 0;
int cmbExp = 0;
// the sum of the polynomials
Node temp = null;
float coeffProd;
int expSum;
if(poly1 == null)
return "Enter a Different Polynomial";
if(poly2 == null)
return "Enter a Different Polynomial";
// while loop if either polynomial runs out of terms. This avoids nullpointerexception
while (polynomial1 != null) {
while(polynomial2 != null){
coeffProd = polynomial1.term.coeff * polynomial2.term.coeff;
expSum = polynomial1.term.degree + polynomial2.term.degree;
temp = new Node(coeffProd, expSum, temp);
polynomial2 = polynomial2.next;
}
polynomial1 = polynomial1.next;
polynomial2 = mult;
}
// my attempt at combining
Node temp2 = temp.next;
while(temp != null){
while(temp2 != null){
if(temp.term.degree == temp2.term.degree){
cmb = temp.term.coeff + temp2.term.coeff;
cmbExp = temp.term.degree;
}
temp2 = temp2.next;
temp3 = new Node(cmb,cmbExp,temp3);
}
temp = temp.next;
}
// Reverses the Polynomial into the correct sequence
Node flip = temp;
Node ans = null;
while (flip != null)
{
if (flip.term.coeff == 0)
{
flip = flip.next;
continue;
}
else
{
ans = new Node(flip.term.coeff, flip.term.degree, ans);
flip = flip.next;
}
}
if (ans == null)
return null;
else
{
return ans;
}
}
Result:
32.0x^9 + 16.0x^8 + -12.0x^6 + 36.0x^5 + -16.0x^7 + -8.0x^6 + 6.0x^4 + -18.0x^3 + 16.0x^5 + 8.0x^4 + -6.0x^2 + 18.0x + 24.0x^4 + 12.0x^3 + -9.0x + 27.0
I need to combine these like terms.

The combining can be simplified if you iterate through the degrees. This also guarantees that the combined polynomial is created with the degrees in sequential order.
The following working code demonstrates one possible way to combine, and create the desired result.
public Node multiply(Node poly1, Node poly2) {
if (poly1 == null || poly2 == null)
return null;
Node polynomial1 = poly1;
Node polynomial2 = poly2;
Node allTerms = null;
float coeffProd;
int expSum;
int maxDegree = 0;
while (polynomial1 != null) {
while (polynomial2 != null) {
coeffProd = polynomial1.term.coeff * polynomial2.term.coeff;
expSum = polynomial1.term.degree + polynomial2.term.degree;
allTerms = new Node(coeffProd, expSum, allTerms);
if (expSum > maxDegree)
maxDegree = expSum;
polynomial2 = polynomial2.next;
}
polynomial1 = polynomial1.next;
polynomial2 = poly2;
}
/* Combine terms */
Node combinedNode = null;
for (int i = 0; i<= maxDegree; i++) {
Node temp = allTerms;
float fSum = 0;
while (temp != null) {
if (temp.term.degree == i)
fSum+=temp.term.coeff;
temp = temp.next;
}
if (fSum != 0)
combinedNode = new Node(fSum, i, combinedNode);
}
return combinedNode;
}

Related

Int not able to accomodate the result and hence program fails

This is a leetcode problem number 2. I guess I am really dumb not able to solve this. I encountered a particular issue where I am not able to solve it for the test case
[9]
[9,9,9,9,9,9,9,9,9,1]
The issue is that my program is returning 1410065399 instead of 9999999991 when I try to make a digit out of the link list. I have mentioned the actual problem statement and my solution alongside. Please provide some light so that I can understand what went wrong.
PROBLEM
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Actual Code which I wrote
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
ListNode first;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int finalResult = returnNumber(l1)+returnNumber(l2);
System.out.println(returnNumber(l1));
System.out.println(returnNumber(l2));
int length=0;
if(finalResult!=0){
length = (int)(Math.log10(finalResult)+1);
}else{
length =1;
}
for(int i=length-1;i>=0;i--){
generateList(finalResult,i);
}
return first;
}
public void generateList(int finalResult,int number){
ListNode oldNode = first;
first = new ListNode((finalResult / (int)Math.pow(10,number)) % 10);
System.out.println((finalResult / (int)Math.pow(10,number)) % 10);
first.next = oldNode;
}
public int returnNumber(ListNode list){
int i=0;
int base = 10;
int total = 0;
while(list!=null){
total=total+(list.val*(int)Math.pow(10,i));
i++;
list = list.next;
}
return total;
}
}
public class MainClass {
public static int[] stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return new int[0];
}
String[] parts = input.split(",");
int[] output = new int[parts.length];
for(int index = 0; index < parts.length; index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
}
public static ListNode stringToListNode(String input) {
// Generate array from the input
int[] nodeValues = stringToIntegerArray(input);
// Now convert that list into linked list
ListNode dummyRoot = new ListNode(0);
ListNode ptr = dummyRoot;
for(int item : nodeValues) {
ptr.next = new ListNode(item);
ptr = ptr.next;
}
return dummyRoot.next;
}
public static String listNodeToString(ListNode node) {
if (node == null) {
return "[]";
}
String result = "";
while (node != null) {
result += Integer.toString(node.val) + ", ";
node = node.next;
}
return "[" + result.substring(0, result.length() - 2) + "]";
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
ListNode l1 = stringToListNode(line);
line = in.readLine();
ListNode l2 = stringToListNode(line);
ListNode ret = new Solution().addTwoNumbers(l1, l2);
String out = listNodeToString(ret);
System.out.print(out);
}
}
}
As the inputs are list instead of an Integer so there isn't a restriction on length of it. So I would suggest looping through the input and collecting the sum of elements as you go through it and creating the result list. (don't forget the carry which can be of multiple digits)
Below you can find my code for reference.
(Any suggestions will always be welcomed)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, node = null;
int carry = 0, sum = 0;
while (!(l1 == null && l2 == null)) {
// both not null
if (l1 != null && l2 != null) {
sum = (l1.val + l2.val + carry) % 10;
carry = (l1.val + l2.val + carry) / 10;
l1 = l1.next;
l2 = l2.next;
}
// l1==null
else if (l1 == null && l2 != null) {
sum = (l2.val + carry) % 10;
carry = (l2.val + carry) / 10;
l2 = l2.next;
}
// l2==null
else if (l1 != null && l2 == null) {
sum = (l1.val + carry) % 10;
carry = (l1.val + carry) / 10;
l1 = l1.next;
}
// both null
else {
// break out of the loop
}
if (head == null) {
head = new ListNode(sum);
node = head;
} else {
node.next = new ListNode(sum);
node = node.next;
}
}
if (carry > 0) {
while (carry > 0) {
int curr = carry % 10;
node.next = new ListNode(curr);
node = node.next;
carry = carry / 10;
}
}
return head;
}

Can't print out Add two numbers in Java

I can't return the value from the function AddTwoNumber to main. I have already checked the result in the function and it is correct. However, when I pass the value from AddTwoNumber into ListNode start, it doesn't print anything. I think the problem is happening here:
ListNode dummy = new ListNode(0);
ListNode node = dummy;
but I'm don't know how to solve it.
ListNode.cs:
class ListNode {
public int data; // data stored in this node
public ListNode next; // link to next node in the list
// post: constructs a node with data 0 and null link
public ListNode() {
this(0, null);
}
// post: constructs a node with given data and null link
public ListNode(int data) {
this(data, null);
}
// post: constructs a node with given data and given link
public ListNode(int data, ListNode next) {
this.data = data;
this.next = next;
}
}
Main.cs:
public static void main(String[] args) {
ListNode first = new ListNode(8,
new ListNode(9,
new ListNode(7 )));
ListNode second = new ListNode(3,
new ListNode(5,
new ListNode(6 )));
ListNode start = AddTwoNumber(first,second);
while (start!=null) {
System.out.println(start.next);
start=start.next;
}
}
public static ListNode AddTwoNumber(ListNode first, ListNode second) {
ListNode dummy = new ListNode(0);
ListNode node = dummy;
int Digitsten = 0;
int sum = 0;
//Once fit first&second =null & Digitsten=0,the code can stop
while (first != null || second != null || Digitsten != 0) {
if (first != null && second != null) {
sum += first.data + second.data + Digitsten;
} else if (first!= null) {
sum += first.data + Digitsten;
} else if (second!= null) {
sum += second.data + Digitsten;
} else {
sum=Digitsten; `enter code here`
}
int DigitsOne = sum % 10;
Digitsten = sum / 10;
node = new ListNode(DigitsOne);
node = node.next;
if (first == null) {
first = null;
} else {
first = first.next;
}
if (second == null) {
second = null;
} else {
second = second.next;
}
sum = 0;
}
return dummy.next; //return the value to dummy ListNode
}
The real problem is inside your AddTwoNumber method.
You can't make node pointing to a new node, you should make its next pointing to a new node, before you move to next.
public static ListNode AddTwoNumber(ListNode first, ListNode second){
ListNode dummy = new ListNode(0);
ListNode node = dummy;
int Digitsten = 0;
int sum = 0;
while (first != null || second != null || Digitsten != 0)
{
if (first != null && second != null)
{
sum += first.data + second.data + Digitsten;
}
else if (first!= null)
{
sum += first.data + Digitsten;
}
else if (second!= null)
{
sum += second.data + Digitsten;
}
else
{
sum=Digitsten; `enter code here`
}
int DigitsOne = sum % 10;
Digitsten = sum / 10;
// LOOK HERE!!!
node.next = new ListNode(DigitsOne);
node = node.next;
if (first == null)
{
first = null;
}
else
first = first.next;
if (second == null)
{
second = null;
}
else
{
second = second.next;
}
sum=0;
}
return dummy.next;//return the value to dummy ListNode

Infinite Integer Linked List NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm writing a program that creates an infinitely long integer by making each number in the integer its own node.
For example: 123,456 = [1]->[2]->[3]->[4]->[5]->[6]
Also, I need to be able to add the contents of two infinite integers together.
For example: [1]->[2]->[3]->[4]->[5]->[6] + [1]->[2]->[3]
= [1]->[2]->[3]->[5]->[7]->[9]
However, when I try to reversely traverse one of the linked lists, I get a NullPointerException after the first loop through;
while((currentOne != null) && (currentTwo != null)) {
// for(int i = firstOperand.getNumberOfDigitsWithZeroes(); i>0; i--)
if(currentOne.data > currentTwo.data) {
tempResult = currentOne.data - currentTwo.data;
//result = tempResult + result;
returnResult.addToFront(tempResult);
} else if(currentOne.data < currentTwo.data) {
currentOne.previous.data -= 1;
currentOne.data += 10;
tempResult = currentOne.data - currentTwo.data;
//result = tempResult + result;
returnResult.addToFront(tempResult);
} else if((currentOne == firstOperand.firstNode && currentTwo == secondOperand.firstNode) &&
currentOne.data - currentTwo.data == 0) {
break;
} else {
returnResult.addToFront(0);
}
currentOne = currentOne.previous;
currentTwo = currentTwo.previous;
}
firstOperand is the linked list of the number 100000000000000000000. currentOne is a node initialized to the last node of the firstOperand. currentTwo is a node initialized to the last node of the secondOperand which has the contents of 000000000000000000001. The error is located in the line
if(currentOne.data > currentTwo.data)
The error occurs after only the second run through of the loop, and i'm not sure why, because when printed in string form, the secondOperand shows the full 000000000000000000001. So, I'm not sure why i'm getting the null pointer exception instead of currentTwo.data being equal to 0.
Here is the constructor for an InfiniteInteger object
public LInfiniteInteger(String s)
{
// TO DO
int newDigit = 0;
isNegative = false;
numberOfDigits = 0;
middlePosition = 0;
firstNode = null;
middleNode = null;
lastNode =null;
for(int i =0; i<s.length(); i++)
{
newDigit = (int)s.charAt(i) - 48;
if((newDigit >= 0) && (newDigit <= 9))
{
// this.add(newDigit);
if(firstNode == null)
{
firstNode = new Node(null, newDigit, null);
lastNode = firstNode;
}
else
{
Node newNode = new Node(lastNode, newDigit, null);
lastNode.next = newNode;
lastNode = newNode;
}
numberOfDigits++;
if(numberOfDigits %2 == 1);
{
if(middleNode == null)
{
middleNode = firstNode;
}
else
{
middleNode = middleNode.next;
}
middlePosition++;
}
}
else if((newDigit == ((int)'-') - 48))
{
isNegative = true;
}
}
}
This is the full method of where the error occurs:
public InfiniteIntegerInterface minus(final InfiniteIntegerInterface anInfiniteInteger)
{
// TO DO
LInfiniteInteger firstOperand = new LInfiniteInteger(this.toString());
LInfiniteInteger secondOperand = new LInfiniteInteger(anInfiniteInteger.toString());
LInfiniteInteger returnResult = new LInfiniteInteger("");
int tempResult;
boolean resultIsNegative = false;
Node currentOne = firstOperand.lastNode;
Node currentTwo = secondOperand.lastNode;
while(firstOperand.getNumberOfDigitsWithZeroes() > secondOperand.getNumberOfDigitsWithZeroes())
{
Node temp = new Node(0);
temp.next=secondOperand.firstNode;
secondOperand.firstNode = temp;
secondOperand.addNumberOfDigits();
}
while(firstOperand.getNumberOfDigitsWithZeroes() < secondOperand.getNumberOfDigitsWithZeroes())
{
Node temp = new Node(0);
temp.next=firstOperand.firstNode;
firstOperand.firstNode = temp;
firstOperand.addNumberOfDigits();
}
if((firstOperand.isNegative == false) && (secondOperand.isNegative == false))
{
if(firstOperand.compareMag(secondOperand) == 1)
{
//algorithm
//System.out.println(currentTwo.data);
//System.out.println(secondOperand.toString());
for(int i = secondOperand.getNumberOfDigitsWithZeroes(); i > 0; i--)
{
System.out.println(currentOne.data);
currentOne = currentOne.previous;
}
currentOne = firstOperand.lastNode;
while((currentOne != null) && (currentTwo != null))
// for(int i = firstOperand.getNumberOfDigitsWithZeroes(); i>0; i--)
{
if(currentOne.data > currentTwo.data)
{
tempResult = currentOne.data - currentTwo.data;
//result = tempResult + result;
returnResult.addToFront(tempResult);
}
else if(currentOne.data < currentTwo.data)
{
currentOne.previous.data -= 1;
currentOne.data += 10;
tempResult = currentOne.data - currentTwo.data;
//result = tempResult + result;
returnResult.addToFront(tempResult);
}
else if((currentOne == firstOperand.firstNode && currentTwo == secondOperand.firstNode) && currentOne.data - currentTwo.data == 0)
{
break;
}
else
{
returnResult.addToFront(0);
}
currentOne = currentOne.previous;
currentTwo = currentTwo.previous;
}
if(currentOne == null)
{
while(currentTwo != null)
{
//result = currentTwo.data + result;
returnResult.addToFront(currentTwo.data);
currentTwo = currentTwo.previous;
}
}
else if(currentTwo == null)
{
while(currentTwo != null)
{
//result = currentTwo.data + result;
returnResult.addToFront(currentTwo.data);
currentTwo = currentTwo.previous;
}
}
return returnResult;
}
else if(firstOperand.compareMag(secondOperand) == 0)
{
returnResult.add(0);
return returnResult;
}
else
{
LInfiniteInteger tempReturnResult = new LInfiniteInteger(secondOperand.minus(firstOperand).toString());
Node currentOneInner = tempReturnResult.firstNode;
while(currentOneInner != null)
{
returnResult.add(currentOneInner.data);
currentOneInner = currentOneInner.next;
}
returnResult.isNegative = true;
return returnResult;
}
}
else if((firstOperand.isNegative == false) && (secondOperand.isNegative == true))
{
secondOperand.isNegative = false;
LInfiniteInteger tempReturnResult = new LInfiniteInteger(firstOperand.plus(secondOperand).toString());
Node currentOneInner = tempReturnResult.firstNode;
while(currentOneInner != null)
{
returnResult.add(currentOneInner.data);
currentOneInner = currentOneInner.next;
}
return returnResult;
}
else if((firstOperand.isNegative == true) && (secondOperand.isNegative == false))
{
firstOperand.isNegative = false;
LInfiniteInteger tempReturnResult = new LInfiniteInteger(firstOperand.plus(secondOperand).toString());
Node currentOneInner = tempReturnResult.firstNode;
while(currentOneInner != null)
{
returnResult.add(currentOneInner.data);
currentOneInner = currentOneInner.next;
}
returnResult.isNegative = true;
return returnResult;
}
else
{
if(firstOperand.compareMag(secondOperand) == -1)
{
firstOperand.isNegative = false;
secondOperand.isNegative = false;
LInfiniteInteger tempReturnResult = new LInfiniteInteger(firstOperand.minus(secondOperand).toString());
Node currentOneInner = tempReturnResult.firstNode;
while(currentOneInner != null)
{
returnResult.add(currentOneInner.data);
currentOneInner = currentOneInner.next;
}
return returnResult;
}
else if(firstOperand.compareMag(secondOperand) == 0)
{
returnResult.add(0);
return returnResult;
}
else
{
firstOperand.isNegative = false;
secondOperand.isNegative = false;
LInfiniteInteger tempReturnResult = new LInfiniteInteger(firstOperand.minus(secondOperand).toString());
Node currentOneInner = tempReturnResult.firstNode;
while(currentOneInner != null)
{
returnResult.add(currentOneInner.data);
currentOneInner = currentOneInner.next;
}
returnResult.isNegative = true;
return returnResult;
}
}
}
I'm trying to subtract 1000000000000000 and 0000000000000001.
Here's my Node class:
private class Node
{
private int data;
private Node next;
private Node previous;
private Node(Node previousNode, int aData, Node nextNode)
{
previous = previousNode;
data = aData;
next = nextNode;
}
private Node(int aData)
{
this(null, aData, null);
}
}
The problem may happens because you fail to initialize the member variable data. Check your code carefully and debug it step by step.
Your constructor doesn't take care of member previous, or is this in the Node constructor?

How to sort a linked list of Polynomials by degree?

Currently I've written a method that adds two polynomials together. Poly1 and Poly2. The logic of the method is as follows, first it adds all matching degree terms from Poly1 and Poly2, then it adds all non-matching terms from Poly1, and finally adds all non-matching terms from Poly2. But because of this, the terms are out of order.
Polynomial answer = new Polynomial();
for (Node firstPoly = poly; firstPoly != null; firstPoly = firstPoly.next){
boolean polyAdded = false;
for (Node secondPoly = p.poly; secondPoly != null; secondPoly = secondPoly.next){
if (firstPoly.term.degree == secondPoly.term.degree){
answer = addToRear(answer, (firstPoly.term.coeff + secondPoly.term.coeff), firstPoly.term.degree, null);
if (answer.poly.term.coeff == 0){
answer.poly = null;
}
polyAdded = true;
}
}
if (polyAdded == false){
answer = addToRear(answer, firstPoly.term.coeff, firstPoly.term.degree, null);
if (answer.poly.term.coeff == 0){
answer.poly = null;
}
}
}
for (Node secondPoly = p.poly; secondPoly != null; secondPoly = secondPoly.next){
boolean match = false;
for (Node answerPoly = answer.poly; answerPoly != null; answerPoly = answerPoly.next){
if (secondPoly.term.degree == answerPoly.term.degree){
match = true;
break;
}
}
if (match == false){
answer = addToRear(answer, secondPoly.term.coeff, secondPoly.term.degree, null);
}
}
return answer;
//alt + shift + r
}
If this code outputs:
8.0x^4 + 4.0x^5 + 2.0x^3 + -1.0x + 12.0
the linked list is represented as such:
(coefficient, degree) // (12, 0) -> (-1, 1) -> (2, 3) -> (4, 5) -> (8, 4)
I want to now sort my answer polynomial by order of degree. The linked list should be represented like this:
(coefficient, degree) // (12, 0) -> (-1, 1) -> (2, 3) -> (8, 4) -> (4, 5)
EDIT: Found the solution on my own. Here is the sorting method I created:
private Polynomial sortByDegree(Polynomial p){
Node prev = p.poly;
Node current = p.poly.next;
while (current != null){
if (current.term.degree < prev.term.degree){
int temp = current.term.degree;
current.term.degree = prev.term.degree;
prev.term.degree = temp;
float temp2 = current.term.coeff;
current.term.coeff = prev.term.coeff;
prev.term.coeff = temp2;
prev = p.poly;
current = p.poly.next;
}
prev = prev.next;
current = current.next;
}
return p;
}
Thanks everyone!
Can suggest two approaches:
First. Fetch linked list into array list (stack), sort array list, rebuild as linked list.
Second. Use following algo:
void sortPoly(Polynomial answer) {
float lowerMargin = 0;
Node head = null, tail = null;
while (answer.poly != null) {
Node next = detouchMin(lowerMargin, answer);
lowerMargin = next.term.degree;
if (tail != null) {
tail.next = next;
tail = next;
else {
head = next;
tail = next;
}
}
answer.poly = head;
}
Node detouchMin(float lowerMargin, Polynomial answer) {
float min = Float.inf;
Node n = null;
Node t = answer.poly;
while (t != null) {
if ((t.term.degree > lowerMargin) && (t.term.degree < min)) {
n = t;
min = n.term.degree;
}
t = t.next;
}
if (n != null) {
Node t = answer.poly, prev = null;
while (t != null) {
if (t == n) {
if (prev != null)
answer.poly = t.next;
else
prev.next = t.next;
}
prev = t;
t = t.next;
}
}
return n;
}
Note: code not tested

When I construct a second new Polynomial(linked list) class, the first one takes the second one's values

package polynomial;
/**
*
* #author Steven
*/
public class Polynomial
{
private float data;
protected static Polynomial head;
private Polynomial link;
/**
* #param args the command line arguments
*/
public Polynomial(float[] data)
{
head = null;
if(data.length == 1)
head = insertAtFront(head, data[0]);
for(int i = data.length-1; i >= 0; i--)
{
System.out.println(head);
head = insertAtFront(head, data[i]);
}
}
public Polynomial(float data, Polynomial link)
{
this.link = link;
this.data = data;
}
public static Polynomial add(Polynomial p, Polynomial p2)
{
if(p.length() > p2.length())
{
while(p.length() != p2.length())
{
insertAtFront(p2, 0);
}
for(Polynomial poly = p; poly != null && p2 != null; poly = poly.link)
{
p2.data = (p2.data + poly.data);
p2 = p2.link;
}
}
else if(p2.length() > p.length())
{
while(p2.length() != p.length())
{
insertAtFront(p, 0);
}
for(Polynomial poly = p; poly != null && p2 != null; poly = poly.link)
{
p2.data = (p2.data + poly.data);
p2 = p2.link;
}
}
else
{
for(Polynomial poly = p; poly != null && p2 != null; poly = poly.link)
{
p2.data = (p2.data + poly.data);
p2 = p2.link;
}
}
return p2.head;
}
public float evaluate(float x)
{
int i = head.length()-1;
float y = 0;
for(Polynomial poly = head; poly != null; poly = poly.link)
{
if(poly.link == null)
y += poly.data;
else
y += (poly.data * (float)(Math.pow(x, i)));
i -= 1;
}
return y;
}
#Override
public String toString()
{
int i = 1;
String polyString = "blank";
for(Polynomial poly = head; poly != null; poly = poly.link)
{
if(polyString.equalsIgnoreCase("blank"))
{
if(poly.data != 0)
polyString = poly.data + "x^" + (poly.length()-i) + " + ";
else if(poly.data == 1)
polyString = "x^" + (poly.length()-i) + " + ";
else
polyString = poly.data + "x^" + (poly.length()-i) + " + ";
}
else
{
if(poly.link == null)
{
if(poly.data != 0)
polyString = polyString + poly.data;
else if(poly.data == 1)
polyString = polyString + "x";
else
polyString = polyString + poly.data + "x^" + (poly.length()-i);
}
else
{
if(poly.data != 0)
polyString = polyString + poly.data + "x^" + (poly.length()-i) + " + ";
else if(poly.data == 1)
polyString = polyString + "x^" + (poly.length()-i) + " + ";
else
;
}
}
i = i + 1;
}
return polyString;
}
public int length()
{
int answer = 0;
for(Polynomial poly = head; poly != null; poly = poly.link)
{
answer++;
}
return answer;
}
private static Polynomial insertAtFront(Polynomial head, float data)
{
return new Polynomial(data, head);
}
}
I have a second class that is just a program to run these methods, and when I create a new Polynomial, and run associated methods, everything appears to run successfully. After I create a new Polynomial, the first Polynomial takes the second one's values. I don't understand 1. where the first-created polynomial's values are going and 2. why it's doing this at all.
protected static Polynomial head;
your head is declared as static - thus there is only one copy of it for all classes! Once your second Polynomial is created, it overrides the head of the first one.
You probably want it to be an instance variable and not a class variable.
Though, doing it will also have its own problems of infinite recursive constructor invokation. To overcome it, you might want to have a different class that holds a Polynomial head as an instance variable, and initialized it only once per list.

Categories

Resources