Polynomial LinkedList formatting - java

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();
}
}

Related

How Do I Process objects in my custom linked list?

I successfully made a linked list, but now I am having trouble processing it. What methods do I need to add to my FoodList class to be able to process my objects? For example, I need to have the user be able to choose to manually add food objects together so I can print a meal. Also, I can't use any collections classes from the java API. It all must be custom.
public static void main(String[] args) {
FoodList list = new FoodList();
boolean keepGoing = true;
int scanResultInt;
try
{
//I/O stream
FileReader fr = new FileReader("foodlist.txt");
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
Food hold = new Food();
while(scan.hasNext()){
list.add(hold = new Food());
String str = scan.next();
//str = scan.next();
hold.setName(str);
str = scan.next();
hold.setGroup(str);
int cal = scan.nextInt();
hold.setNumCal(cal);
double percent = scan.nextDouble();
hold.setPercentDV(percent);
list.add(hold);
}
//System.out.println("" + list.toString());
br.close(); //close I/O stream
}
catch(IOException e){
System.err.println("I/O EXCEPTION: " + e.getMessage());
}
Scanner scan2 = new Scanner(System.in);
do {
System.out.println("---------------------------------------------------------");
System.out.println(" Welcome to the Parkland Meal Selector" );
System.out.println("---------------------------------------------------------");
System.out.println("Enter the number of the menu option you would like to select:");
System.out.println(" 1) List food database");
System.out.println(" 2) Create meal by manual selection");
System.out.println(" 3) Create meal by random selection");
System.out.println(" 4) Remove foods high in calories");
System.out.println(" 5) Exit");
scanResultInt = scan2.nextInt();
switch(scanResultInt) {
case 1: {
System.out.println("" + list.toString());
break;
}
case 2: {
System.out.println("Create-A-Meal Menu\n");
System.out.println("Enter the name of a food you would like to add:\n");
String foodWanted = scan2.next();
/*while( != null){
if(foodWanted.equals());
}*/
/*Food tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
result += tmp.f;
}
return result;*/
}
case 3: {
System.out.println("Create meal by random selection: \n");
break;
}
case 4: {
System.out.println("Remove Food High In Calories: \n");
break;
}
case 5: {
keepGoing = false;
break;
}
}
}
while(keepGoing);
}
Here is my Linked List:
public class FoodList {
// Class fields
private FoodNode head;
private int listCount;
// Private inner class
private class FoodNode
{
public Food f;
public FoodNode next;
public FoodNode(Food f)
{
this.f = f;
this.next = null;
}
}
// Constructor for LinkedList
public FoodList()
{
// Initialize start of the list
head = null;
listCount = 0;
}
// Add method (adds a reservation to the linked list)
public void add(Food f)
{
// Create a new ReservationNode
FoodNode node = new FoodNode(f);
// If this is the first node
if( head == null )
head = node;
else
{
FoodNode tmp = head;
while(tmp.next != null)
tmp = tmp.next;
tmp.next = node;
}
listCount++
}
/*public boolean hasThatFood(String food){
boolean haveThat = false;
FoodNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
if (food == f.getName());
haveThat = true;
}
return haveThat;
}*/
/*public boolean hasNext(){
boolean hasNext = false;
if(head != null) {
hasNext = true;
return hasNext;
}
}*/
#Override
public String toString() {
String result = "My Foods:" + '\n';
// Loop through all the reservation nodes
FoodNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
result += tmp.f;
}
return result;
}
}
And my Food class
public class Food {
private String name;
private String group;
private int numCal;
private double percentDV;
public Food() {//String name, String group, int numCal, double percentDV
/*this.name = name;
this.group = group;
this.numCal = numCal;
this.percentDV = percentDV;*/
name = "";
group = "";
numCal = 0;
percentDV = 0.0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getNumCal() {
return numCal;
}
public void setNumCal(int numCal) {
this.numCal = numCal;
}
public double getPercentDV() {
return percentDV;
}
public void setPercentDV(double percentDV) {
this.percentDV = percentDV;
}
#Override
public String toString() {
return "Food{" +
"name: '" + name + '\'' +
", Food Group: '" + group + '\'' +
", Calories: " + numCal +
", Daily Percent: " + percentDV +
'}';
}
}
I know this is spaghetti code, but this is my last resort. Any help would be appriciated!
To operate on the objects you have to write your custom Iterator. I guess here is nothing criminal to open LinkedList source and look how it works.
Something like this, You can find many resource online,
https://crunchify.com/how-to-implement-a-linkedlist-class-from-scratch-in-java/
Here is one.
public Object getElement(int index)
{
if (index < 0)
return null;
Node Current = null;
if (head != null) {
Current = head.getNext();
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return null;
Current = Current.getNext();
}
return Current.getData();
}
return Current;
}
You have implemented some complicated classes. Inner logic of its is not very clear like your issue. So almost any answer will not cover your needs.
If I would you I would try recommend the logic using java core tools (without implementing classes, that implemented in best way LinkedList, ArrayList...). Logic should be converted into some structural solution. For example:
enter point creates and calls your stream service to handle provided input stream;
stream handler should manipulate builder;
builder result have to be collected into composite;
and so on...
If you provide your logic in more structural way you would ask more clear question pointing the issue. Also I believe your question will disappear after this preparation.
Also I would recommend you to get familiar with next GoF patterns: builder, factory method, composite, strategy.

Tree iterator in Java

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

Adding a number in between a Range

I have made a program that takes a user's input for start number, end number, and an increment. This is added to a Range (linked-list). I want to add a number that the user inputted to this Range and put the inputted number in between each number.
Main:
public class PDEMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a start number: ");
Integer startNum = input.nextInt();
System.out.print("Enter end number: ");
Integer endNum = input.nextInt();
System.out.print("Enter increment: ");
Integer increment = input.nextInt();
Range obj = new Range(startNum, endNum, increment);
obj.display();
System.out.print(" Enter 1 for take:\n "
+ "Enter 2 for drop:\n "
+ "Enter 3 for repeat:\n "
+ "Enter 4 for interpose: ");
Integer number = input.nextInt();
if(number == 1) {
obj.take();
}
if(number == 2) {
obj.drop();
}
if(number == 3) {
obj.repeat();
}
if(number == 4) {
obj.interpose();
}
}
}
Range:
public class Range implements Cloneable {
private Integer data; // holds the data
private Range link; //holds the link
private Range head; //refers to head of linked list
private Integer startValue;
private Integer endValue;
private Scanner input;
public Range(Integer data, Range link) {
this.data = data;
this.link = link;
}
public Range(Integer data, Range link, Range head) {
this.data = data;
this.link = link;
this.head = head;
}
public Range(Integer start, Integer end,Integer increment) {
if(start == null) {
startValue = 0;
}
if(increment == null) {
if(start < end) {
increment++;
} else {
increment--;
}
}
for (int i = start; i <= end; i+= increment) {
addNodeAfter(i);
}
}
public Integer getData() {
return data;
}
public void setData(Integer data) {
this.data = data;
}
public Range getLink() {
return link;
}
public void setLink(Range link) {
this.link = link;
}
public Range getHead() {
return head;
}
public void setHead(Range head) {
this.head = head;
}
I have the following code for this interpose method:
public void interpose() {
System.out.println("What number would you like to interpose? ");
Integer answer = input.nextInt();
Range cursor = head;
for (int i = 0; i <= answer; i++) {
System.out.print(cursor.getData() + " ");
this.link = new Range(answer, this.link);
cursor = cursor.getLink();
}
System.out.print("New Range: ");
display();
modify();
anotherRange();
}
I get a NullPointerException at Integer answer = input.nextInt();
Any tips on why I get this Exception and also if my logic is correct?
Try to add Scanner class into interpose() method like this:
Scanner input = new Scanner(System.in);
Integer answer = input.nextInt();

java - Queue method help needed

I am doing a project in Java and I need to create a queue method.
Every time someone is added to a room, they need to be added to the queue.
I nee to create my own queue object in your program and write methods within the object to add to queue and take from queue.
Every time a customer is added to a room it should use the
queue object method to add the customer’s name to the queue.
When the user selects to display the names of the last 3 customers the code should remove them from the queue one by one (first in first out) and display them as they are removed.
The queue should be based on an array and hold 7 items.
When the queue items reach the end of the array they should be added to the start or the array.
If the queue becomes full then an error message should be displayed and the oldest queue item should be automatically removed and displayed.
This is the main body:
package hotelcoursework2;
import java.util.*;
public class HotelCourseWork2 {
public static void main(String[] args) {
Room[] myHotel = new Room[10];
Queue mq = new Queue();
int guests = 0;
String roomName = null;
int roomNum = 0;
String letter = "";
for (int i = 0; i < myHotel.length; i++) {
myHotel[i] = new Room();
}
do {
System.out.println("Press E to display empty rooms");
System.out.println("Press A to add customers to room");
System.out.println("Press V to view all rooms ");
System.out.println("Press D to delete customers from rooms");
System.out.println("Or enter 1 to add to queue, 2 to take from queue or 3 display queue");
System.out.println("Press S to save");
System.out.println("Press L to load");
System.out.println("Press X to exit");
System.out.println("Enter a Letter: ");
Scanner scan = new Scanner(System.in);
letter = scan.next();
if (letter.equals("A")) {
add(myHotel, roomNum, roomName, guests);
mq.addqueue();
}
if (letter.equals("V")) {
view(myHotel);
}
if (letter.equals("E")){
empty(myHotel);
}
if(letter.equals("D")){
delete(myHotel, roomNum);
mq.takequeue();
}
if (letter.equals("S")){
}
if(letter.equals("3")){
mq.displayqueue();
}
} while (letter.charAt(0) != 'X');
System.out.println("Exit successfull");
}
private static void add(Room myHotel[], int roomNum, String roomName, int guests) {
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-9) or 10 to stop:");
roomNum = input.nextInt();
if (roomNum == 10) {
System.out.println("Exit successful");
System.exit(0);
}
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
System.out.println("Enter how many guests: ");
guests = input.nextInt();
myHotel[roomNum].setGuestsInRoom(guests);
System.out.println("Add customers to queue: ");
for (int i = 0; i < 10; i++) {
System.out.println("Customer " + myHotel[i].getName() + " has been allocated to room " + i
+ " with " + myHotel[i].getGuestsInRoom() + " guests. ");
}
}
private static void view(Room myHotel[]) {
for (int i = 0; i < 10; i++) {
System.out.println("room " + i + " occupied by " + myHotel[i].getName() );
}
}
private static void empty(Room myHotel[]) {
for (int i = 0; i < 10; i++) {
if (myHotel[i].getName().equals("no-one")) {
System.out.println("room " + i + " is empty");
}
}
}
private static void delete(Room myHotel[], int roomNum){
Scanner input = new Scanner(System.in);
System.out.println("Enter room number you want to delete a customer from: ");
roomNum = input.nextInt();
myHotel[roomNum].setName("no-one");
}
}
This is the class I have created for the queue but now I am stuck.The queue should be first in first out.
package hotelcoursework2;
import java.util.Scanner;
public class Queue {
// be careful - this queue can go over the end of the array
//the array should be used in a circular way
private static String qitems[] = new String[7];
private static int front = 0, end = 0;
static void addqueue() {
Scanner input = new Scanner(System.in);
System.out.print("Enter someone to the queue :");
qitems[end] = input.next();
end++;
}
static void takequeue() {
if (end > front) {
System.out.println("Person remove :" + qitems[front]);
front++;
} else {
System.out.println("Empty queue");
}
}
static void displayqueue() {
System.out.println("Queue display: ");
for (int look = front; look < end; look++) {
System.out.print(" " + qitems[look]);
}
System.out.println("");
}
}
So basically you want to know how to implement a simple queue.
Unless you have to, using an array is more complicated because you have to deal with resizing the array and moving its contents about.
The simplest queue structure is a linked list, like this:
public class Queue<T>
{
private Node head;
private Node tail;
public void add(T value)
{
if (head == null)
{
head = new Node(null, value);
tail = head;
}
else
{
tail = new Node(tail, value);
}
}
public T peek()
{
return head == null ? null : head.value;
}
public T take()
{
if (head == null)
{
return null;
}
else
{
T value = head.value;
head = head.next;
return value;
}
}
#Override
public String toString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
Node current = head;
while (current != null)
{
stringBuilder.append(current.value).append(",");
current = current.next;
}
return stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), "]").toString();
}
private class Node
{
private Node next;
private T value;
public Node(Node previous, T value)
{
this.value = value;
if (previous != null)
{
previous.next = this;
}
}
}
}
This class keeps reference to the head and tail Nodes adjusting references in the Node chain when new values are added and modifying the head reference when values are taken.

Adding Polynomials (Linked Lists)......Bug Help

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();

Categories

Resources