I have written a program that creates nodes that in this class are parts of polynomials and then the two polynomials get added together to become one polynomial (list of nodes). All my code compiles so the only problem I am having is that the nodes are not inserting into the polynomial via the insert method I have in polynomial.java and when running the program it does create nodes and displays them in the 2x^2 format but when it comes to add the polynomials together it displays o as the polynomials, so if anyone can figure out whats wrong and what I can do to fix it it would be much appreciated.
Here is the code:
import java.util.Scanner;
class Polynomial{
public termNode head;
public Polynomial()
{
head = null;
}
public boolean isEmpty()
{
return (head == null);
}
public void display()
{
if (head == null)
System.out.print("0");
else
for(termNode cur = head; cur != null; cur = cur.getNext())
{
System.out.println(cur);
}
}
public void insert(termNode newNode)
{
termNode prev = null;
termNode cur = head;
while (cur!=null && (newNode.compareTo(cur)<0))
{
prev = null;
cur = cur.getNext();
}
if (prev == null)
{
newNode.setNext(head);
head = newNode;
}
else
{
newNode.setNext(cur);
prev.setNext(newNode);
}
}
public void readPolynomial(Scanner kb)
{
boolean done = false;
double coefficient;
int exponent;
termNode term;
head = null; //UNLINK ANY PREVIOUS POLYNOMIAL
System.out.println("Enter 0 and 0 to end.");
System.out.print("coefficient: ");
coefficient = kb.nextDouble();
System.out.println(coefficient);
System.out.print("exponent: ");
exponent = kb.nextInt();
System.out.println(exponent);
done = (coefficient == 0 && exponent == 0);
while(!done)
{
Polynomial poly = new Polynomial();
term = new termNode(coefficient,exponent);
System.out.println(term);
poly.insert(term);
System.out.println("Enter 0 and 0 to end.");
System.out.print("coefficient: ");
coefficient = kb.nextDouble();
System.out.println(coefficient);
System.out.print("exponent: ");
exponent = kb.nextInt();
System.out.println(exponent);
done = (coefficient==0 && exponent==0);
}
}
public static Polynomial add(Polynomial p, Polynomial q)
{
Polynomial r = new Polynomial();
double coefficient;
int exponent;
termNode first = p.head;
termNode second = q.head;
termNode sum = r.head;
termNode term;
while (first != null && second != null)
{
if (first.getExp() == second.getExp())
{
if (first.getCoeff() != 0 && second.getCoeff() != 0);
{
double addCoeff = first.getCoeff() + second.getCoeff();
term = new termNode(addCoeff,first.getExp());
sum.setNext(term);
first.getNext();
second.getNext();
}
}
else if (first.getExp() < second.getExp())
{
sum.setNext(second);
term = new termNode(second.getCoeff(),second.getExp());
sum.setNext(term);
second.getNext();
}
else
{
sum.setNext(first);
term = new termNode(first.getNext());
sum.setNext(term);
first.getNext();
}
}
while (first != null)
{
sum.setNext(first);
}
while (second != null)
{
sum.setNext(second);
}
return r;
}
}
Here is my Node class:
class termNode implements Comparable
{
private int exp;
private double coeff;
private termNode next;
public termNode(double coefficient, int exponent)
{
coeff = coefficient;
exp = exponent;
next = null;
}
public termNode(termNode inTermNode)
{
coeff = inTermNode.coeff;
exp = inTermNode.exp;
}
public void setData(double coefficient, int exponent)
{
coefficient = coeff;
exponent = exp;
}
public double getCoeff()
{
return coeff;
}
public int getExp()
{
return exp;
}
public void setNext(termNode link)
{
next = link;
}
public termNode getNext()
{
return next;
}
public String toString()
{
if (exp == 0)
{
return(coeff + " ");
}
else if (exp == 1)
{
return(coeff + "x");
}
else
{
return(coeff + "x^" + exp);
}
}
public int compareTo(Object other)
{
if(exp ==((termNode) other).exp)
return 0;
else if(exp < ((termNode) other).exp)
return -1;
else
return 1;
}
}
And here is my Test class to run the program.
import java.util.Scanner;
class PolyTest{
public static void main(String [] args)
{
Scanner kb = new Scanner(System.in);
Polynomial r;
Polynomial p = new Polynomial();
System.out.println("Enter first polynomial.");
p.readPolynomial(kb);
Polynomial q = new Polynomial();
System.out.println();
System.out.println("Enter second polynomial.");
q.readPolynomial(kb);
r = Polynomial.add(p,q);
System.out.println();
System.out.print("The sum of ");
p.display();
System.out.print(" and ");
q.display();
System.out.print(" is ");
r.display();
}
}
A few suggestions:
Class names by convention starts with uppercase, e.g. TermNode
Use generics, i.e. TermNode implements Comparable<TermNode>
In fact, it's probably even better to have Node<Term> instead
Bugs I saw:
prev = null; in insert
Should be prev = cur;
Consider factoring this out to a helper find-like method
In readPolynomial, you're creating a new Polynomial every iteration, and doesn't do anything to this.
You want to either insert terms into this, or keep one Polynomial that you return at the end of a static readPolynomial method
while (first != null) sum.setNext(first);
What are you trying to accomplish here? This is an infinite loop!
More suggestions:
It may be easier/more readable/etc to do add in two passes:
merge polynomials first, making sure terms are properly ordered
3x+1 and 2x+2 merges to 3x+2x+1+2
Then simplify by merging any consecutive pairs of terms that have the same exponent
3x+2x simplifies to 5x
Once you get it working, consider optimizing it to add in one pass if necessary
In fact, the polynomial merging can be done easily in O(N^2) using insert
Get it correct first, optimize to O(N) later
While debugging/developing, print out the polynomials often. Do it after you read it. Do it after insertion. Do it after the first pass of add. Do it after the second pass.
One bug I can see right away is: while traversing the list you need to save the current node cur to prev before you move on so. But you are assigning null to prev all the time:
while (cur!=null && (newNode.compareTo(cur)<0)) {
prev = null;// <---- should be prev = cur;
cur = cur.getNext();
Related
I wrote a recursive backtracking algorithm for the so-called "Coin Change Problem". I store the coin values (int) in a self-written LinkedList ("ll") and each of those LinkedLists is stored inside one master LinkedList ("ll_total"). Now, when I try to print out the LinkedLists inside the master LinkedList, all I get is "LinkedList#1e88b3c". Can somebody tell me how to modify the code, in order to print out the coin values properly?
I would also like the algorithm to chose the LinkedList with the least values stored inside, as it would represent the optimal coin combination for the "coin change problem".
import java.util.Scanner;
public class CoinChange_Backtracking {
static int[] coins = {3, 2, 1};
static int index_coins = 0;
static int counter = 0;
static LinkedList ll = new LinkedList();
static LinkedList ll_total = new LinkedList();
public static void main(String[] args) {
Scanner myInput = new Scanner(System.in);
int amount;
System.out.println("Put in the amount of money: ");
amount = myInput.nextInt();
if (amount < 101) {
//Start recursion and display result.
recursiveFunction(coins, amount, index_coins, ll);
ll_total.show_ll();
} else {
System.out.println("The value must be less than 100!");
}
}
public static LinkedList recursiveFunction(int[] coins, int amount, int index_coins, LinkedList ll) {
//The current coin is being omitted. (If index_coins + 1 is still within range.)
if ((index_coins + 1) < coins.length) {
ll = recursiveFunction(coins, amount, index_coins + 1, ll);
ll_total.insert_ll(ll);
for (int i = 0; i < counter; i++) {
ll.deleteAt(0);
}
counter = 0;
}
//The current coin is not being omitted. (If there is still some change left and value of change isn't lower than value of current coin.)
if (amount != 0) {
if (amount >= coins[index_coins]) {
ll.insert(coins[index_coins]);
counter++;
ll = recursiveFunction(coins, amount - coins[index_coins], index_coins, ll);
}
}
return ll;
}
}
public class LinkedList {
Node head;
public void insert(int data) {
Node node = new Node();
node.data = data;
node.next = null;
if (head == null) {
head = node;
} else {
Node n = head;
while(n.next != null) {
n = n.next;
}
n.next = node;
}
}
public void insert_ll(LinkedList ll) {
Node node = new Node();
node.ll = ll;
node.next = null;
if (head == null) {
head = node;
} else {
Node n = head;
while(n.next != null) {
n = n.next;
}
n.next = node;
}
}
public void deleteAt(int index) {
if(index == 0) {
head = head.next;
} else {
Node n = head;
Node n1 = null;
for (int i = 0; i < index - 1; i++) {
n = n.next;
}
n1 = n.next;
n.next = n1.next;
n1 = null;
}
}
public void show() {
Node node = head;
while(node.next != null) {
System.out.println(node.data);
node = node.next;
}
System.out.println(node.data);
}
public void show_ll() {
Node node = head;
while(node.next != null) {
System.out.println(node.ll);
node = node.next;
}
System.out.println(node.ll);
}
//A toString method I tried to implement. Causes an array error.
/*
public String toString() {
Node n = head.next;
String temp = "";
while (n != null) {
temp = temp + n.data + " ";
n = n.next;
}
return temp;
}
*/
}
public class Node {
int data;
LinkedList ll;
Node next;
}
To answer your question. You are printing the linked list object, see here System.out.println(node.ll);
There are several ways to do it right. One approach is to question why you use Node and LinkedList the way you do ? A node can have a linked list and a linked list can have a node, I believe this is not really what you wanted. Maybe you can make it work, but from a design point of view in my experience it is not good. I find it confusing and it's a great source of bugs.
I try to list some points that caught my eye (or that my IDE had caught for my eyes).
You are not closing the Scanner object. Just close it at the end of the program or use the try-with-resources.
As mentioned before you have linked list that has a node and a node that has a linked list. You are not using that correctly in your program. I recommend to review that approach. It is error prone.
Also simply use the LinkedList of the Java library unless you have a good reason not to. It works fine and offers all you need.
You use many static, global (within the scope of the package) variables. In this case I think you can avoid that. coins does not need to be given as a parameter every time. It should be an immutable object. It is not supposed to change.
...
And I am not sure if it is a backtracking algorithm. It is certainly tree recursive. This just as a side note.
I'd like to propose a solution that looks similar to yours. I'd probably do it differently my way, but then it probably takes time to understand it. I try to adopt your style, which I hope helps. I simplified the program.
In order to print the result, simply write a helper function.
The linked list is an object. You have to make a copy of the list every time you call the recursion in order to work on a dedicated object. Otherwise you modify the same object while recursing different paths.
You can simply use a list of lists. A global list of lists (within package scope), and a list of which you make a copy every time you recurse. When you reach a good base case you add it to the global list. Otherwise just ignore.
import java.util.LinkedList;
import java.util.Scanner;
public class CoinChangeBacktracking {
static final int[] COINS = {3, 2, 1};
static final LinkedList<LinkedList<Integer>> changes = new LinkedList<>();
public static void main(String[] args) {
Scanner myInput = new Scanner(System.in);
int amount;
System.out.println("Put in the amount of money: ");
amount = myInput.nextInt();
if (amount < 101) {
// Start recursion and display result.
recursiveFunction(amount, 0, new LinkedList<>());
print(changes);
} else {
System.out.println("The value must be less than 100!");
}
myInput.close();
}
static void recursiveFunction(int amount, int index,
LinkedList<Integer> list) {
// exact change, so add it to the solution
if (amount == 0) {
changes.add(list);
return;
}
// no exact change possible
if (amount < 0 || index >= COINS.length) {
return;
}
// explore change of amount without current coin
recursiveFunction(amount, index + 1, new LinkedList<>(list));
// consider current coin for change and keep exploring
list.add(COINS[index]);
recursiveFunction(amount - COINS[index], index, new LinkedList<>(list));
}
static void print(LinkedList<LinkedList<Integer>> ll) {
for (LinkedList<Integer> list : ll) {
for (Integer n : list) {
System.out.print(n + ", ");
}
System.out.println();
}
}
}
I have been asked to create a program using a LinkedList that represents a polynomial made up of one or many different Terms. Most everything seems to be working, however I am having some issues getting the resulting polynomial to format the way I would like when printed.
My polynomials are supposed to be formatted in descending order, but are being printed in ascending order. Also when the polynomials are printed, I need to somehow get rid of the very first "+" sign that is in front of the entire polynomial without causing problems with the rest of the "+" signs between each term.
Term Class
public class Term {
private DecimalFormat formatHelper = new DecimalFormat("#.####");
int coeff;
private int exp;
private Term next;
public Term(int exp, int coeff, Term next) {
this.setExp(exp);
this.coeff = coeff;
this.setNext(next);
}
public String toString() {
String format = formatHelper.format(Math.abs(coeff));
if (getExp() == 0)
return format;
else
if (getExp() == 1)
return format + "x";
else
return format + "x^" + getExp();
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public Term getNext() {
return next;
}
public void setNext(Term next) {
this.next = next;
}
Polynomial Class
public class Polynomial {
private double test = 0.0005;
private Term head;
public Polynomial() {
head = null;
}
/**
* Adds a term to the current polynomial with the specified coefficient and exponent
*/
public void addTerm(int exp, int coeff) {
if (Math.abs(coeff) < test)
return;
if (head == null || exp < head.getExp()) {
head = new Term(exp, coeff, head);
return;
}
Term last = null;
Term current = head;
while (current != null && exp > current.getExp()) {
last = current;
current = current.getNext();
}
if (current == null || exp != current.getExp())
last.setNext(new Term(exp, coeff, current));
else {
current.coeff += coeff;
if (Math.abs(current.coeff) < test)
if (last != null)
last.setNext(current.getNext());
else
head = head.getNext();
}
}
/**
* Formats the polynomial
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Term term = head; term != null; term = term.getNext())
if (term.coeff < 0)
buffer.append(" - " + term.toString());
else
buffer.append(" + " + term.toString());
return buffer.toString();
}
/**
* EXTRA CREDIT - Adds two polynomials
*/
public Polynomial add(Polynomial p2) {
Polynomial answer = clone();
for (Term term = p2.head; term != null; term = term.getNext())
answer.addTerm(term.getExp(), term.coeff);
return answer;
}
/**
* Special method used only for extra credit, aids in adding of polynomials
*/
public Polynomial clone() {
Polynomial answer = new Polynomial();
for (Term term = head; term != null; term = term.getNext())
answer.addTerm(term.getExp(), term.coeff);
return answer;
}
Tester Class
public class Prog7 {
public static void main(String[] args)
{
Polynomial p1 = new Polynomial();
Polynomial p2 = new Polynomial();
Scanner keyboard = new Scanner(System.in);
int coeffChoice;
int expChoice;
String userInput = "";
String userInput2 = "";
while(!userInput.equalsIgnoreCase("no")){
System.out.println("Please enter the coefficient of the current term: ");
coeffChoice = keyboard.nextInt();
System.out.println("Please enter the exponent of the current term: ");
expChoice = keyboard.nextInt();
p1.addTerm(expChoice, coeffChoice);
System.out.println("Would you like to add a term to the polynomial?");
userInput = keyboard.next();
}
System.out.println("Time to start building the second polynomial!");
while(!userInput2.equalsIgnoreCase("no")){
System.out.println("Please enter the coefficient of the current term: ");
coeffChoice = keyboard.nextInt();
System.out.println("Please enter the exponent of the current term: ");
expChoice = keyboard.nextInt();
p2.addTerm(expChoice, coeffChoice);
System.out.println("Would you like to add a term to the polynomial?");
userInput2 = keyboard.next();
}
System.out.println( "Polynomial 1" );
System.out.println(p1.toString());
System.out.println();
System.out.println("Polynomial 2");
System.out.println(p2.toString());
System.out.println();
System.out.println("Polynomial Addition.");
System.out.println(p1.add(p2));
}
Example Output
Current Output:
+ 5x^2 + 4x^5 +9x^6
Desired Output:
9x^6 + 4x^5 + 5x^2
Since your list is singly linked, you cannot traverse it in backward direction.
But you could prepend the terms instead of appending them. To get rid of the first '+', return a substring if the 1st term is positive:
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Term term = head; term != null; term = term.getNext()) {
if (term.coeff < 0)
buffer.insert(0, " - " + term.toString());
else
buffer.insert(0, " + " + term.toString());
}
if (buffer.charAt(1) == '+') {
return buffer.substring(2);
else {
return buffer.toString();
}
}
I am trying to add two non negative numbers, the digits of which are stored in reverse order in two separate linked lists. The answer should also be a linked list with digits reversed and no trailing zeros.
I understand that there is a way to solve this question by adding digits and maintaining a carry each time, but I am trying to solve it by using addition operation on numbers.
Here's my code:
/**
* Definition for singly-linked list.
* class ListNode {
* public int val;
* public ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode a, ListNode b) {
if(a==null || b==null){
return null;
}
String num1 = "";
String num2 = "";
ListNode temp1 = a;
ListNode temp2 = b;
while(temp1!=null){
num1 = num1+Integer.toString(temp1.val);
temp1 = temp1.next;
}
new StringBuilder(num1).reverse().toString();
double value1 = Double.parseDouble(num1);
while(temp2!=null){
num2 = num2+Integer.toString(temp2.val);
temp2 = temp2.next;
}
new StringBuilder(num2).reverse().toString();
double value2 = Double.parseDouble(num2);
double result = value1+value2;
String res = String.format("%.0f",result);
ListNode first_node = new ListNode(Character.getNumericValue(res.charAt(0)));
ListNode ans = first_node;
for(int j=1;j<res.length();j++){
ListNode node = new ListNode(Character.getNumericValue(res.charAt(j)));
add(node,ans);
}
return ans;
}
public void add(ListNode node, ListNode ans){
ListNode temp;
temp = ans;
ans = node;
ans.next = temp;
}
}
My code has been giving wrong answers. Can anyone point out the errors?
Your approach is not correct and indirect.
You are trying to do big numbers arithmetics using floating point operations.
As a result - computing errors.
We have:
List<Integer> firstNumber;
List<Integer> secondNumber;
Lets assume firstNumber > secondNumber.
Try this alogrithm:
List<Integer> result = new ArrayList<>();
int i = 0;
int appendix = 0;
for (; i < secondNumber.size(); i++) {
int sum = firstNumber.get(i) + secondNumber.get(i) + appendix;
result.append(sum % 10);
appendix = sum / 10;
}
for (; i < firstNumber.size(); i++) {
int sum = firstNumber.get(i) + appendix;
result.append(sum % 10);
appendix = sum / 10;
}
if (appendix != 0)
result.append(appendix);
return result;
Your add function looks incorrect. You will get you number in the reverse order than what is expected.
Also, your solution is missing the point of the question. Your approach will fail if you have a number with a lot of digits (even double has its limits ~ 2^1024 I think). A linked list representation allows for numbers even bigger.
The correct solution would just iterate through both the lists simultaneously with a carry digit while creating the solution list. If this is a question in an assignment or coding competition, your solution would be judged wrong.
Your add method is wrong, it doesn't build correctly the list. Here is how the final part of your method should look, without the add method:
for(int j=1;j<res.length();j++){
ans.next = new ListNode(Character.getNumericValue(res.charAt(j)));;
ans = ans.next;
}
return first_node;
In your approach, the variable ans is not updating. You can try this:
ans = add(node,ans);
and in your add method, change the method to return ListNode ans
Your approach is not straightforward and wouldn't give you expected results.
Here is a simple approach which wouldn't require much explanation as the addition is simple integer by integer.
Do note that i carry forward when the sum of two integers is greater than 9 else 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]
I have implemented a code which adds elements in a tree and prints them in increasing order. However my aim is to learn iterators and want to replace the inOrder() function with an iterator function. How can I do this?
import java.util.InputMismatchException;
import java.util.Scanner;
import javax.xml.soap.Node;
class Tree
{
public final int mVal;
public Tree mLeft;
public Tree mRight;
public Node next;
public Tree(int val)
{
mVal = val;
}
public void add(int val)
{
if (val < mVal)
{
if (mLeft == null)
mLeft = new Tree(val);
else
mLeft.add(val);
}
else
{
if (val > mVal)
{
if (mRight == null)
mRight = new Tree(val);
else
mRight.add(val);
}
}
}
public String inOrder()
{
return ((mLeft == null) ? "" : mLeft.inOrder())
+ mVal + " "
+ ((mRight == null) ? "" : mRight.inOrder());
}
public static void main(String[] args)
{
Tree t = new Tree(8);
Scanner scanner = new Scanner(System.in);
boolean continueLoop = true; // determines if more input is needed
for (int i = 1; i < 9; ++i)
{
try // read two numbers and calculate quotient
{
System.out.print("Please enter a random integer : ");
int stackInt = scanner.nextInt();
t.add(Integer.valueOf(stackInt));
} // end try
catch (InputMismatchException inputMismatchException){
System.err.printf("\nException: %s\n", inputMismatchException);
scanner.nextLine(); //discard input so user can try again
System.out.println("You must enter integers. Please try again.\n");
} // end catch
}
System.out.println("Values in order = "+ t.inOrder());
}
}
look at this picture
First Step: if node has a left child, visit left child and do the first step with the child
Second Step: node has no left child (or we visited the left child already), add it to the inorder list
Third Step: first step with right child
i didnt test it
#Override
public String toString() {
return String.valueOf(mVal);
}
public String inOrder(Tree root) {
List<Tree> inOrder = new ArrayList<>();
inOrderRecursively(root, inOrder);
return inOrder.toString();
}
private void inOrderRecursively(Tree Node, List<Tree> inOrder) {
if (Node.mLeft != null) {
inOrderIt(Node.mLeft, inOrder);
}
inOrder.add(Node);
if (Node.mRight != null) {
inOrderIt(Node.mRight, inOrder);
}
}
greetings
I have been trying to work on a linked list implementation I thought I had it nailed, but for some reason I can't work out how to add a new node to the list at the start of the list.
This was a polynomial addition method, everything else works as expected, but this section does not work as expected. It returns polynomial with no changes... I think I am missing something really simple but cant see it.
else if (power > polynomial.powerMax())
{
Polynomial newlink = new Polynomial(coefficient,power);
newlink.successor = polynomial;
polynomial = newlink;
}
Whole Method
public class Polynomial
{
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;
}
public static void add(Polynomial polynomial, double coefficient, int power)
{
if (polynomial == null) return;
if (Math.abs(coefficient) < epsilon) coefficient = 0.0;
if (coefficient == 0.0) return;
if (power < 0) return;
if (power < polynomial.powerMin())
{
Polynomial newNode = new Polynomial(coefficient,power);
if (polynomial.successor != null)
{
while (polynomial.successor != null)
{
polynomial.successor = polynomial.successor.successor;
}
polynomial.successor = newNode;
}
else if (polynomial.successor == null )
polynomial.successor = newNode;
}
else if (power > polynomial.powerMax())
{
Polynomial newlink = new Polynomial(coefficient,power);
newlink.successor = polynomial;
polynomial = newlink;
}
else
{
if (power == polynomial.power)
polynomial.coefficient = polynomial.coefficient + coefficient;
}
}
In Java the references of variables are passed by value (link). That means if you assign anything new to the variable polynomial it will not have any effect outside of this method.
String x = "Foo";
public void change (String s) {
s="Bar";
}
System.out.println(x);
change(x);
System.out.println(x);
Will print
Foo
Foo
You need to return the new Polynomial you created from the add method.
public static Polynomial add(Polynomial polynomial, double coefficient, int power) {
...
return polynomial;
}