Вот мой текущий класс для создания узлов, сортировки их в соответствующий список и метод для последующей печати этих списков:
Код: Выделить всё
package polynomialAdder;
public class PolyList {
private PolyNode head;
public PolyList()
{
this.head = null;
}
public PolyList(String poly)
{
this.head = null;
String[] component = poly.split("\\+\\-"); //split based on "+" and "-" operators
for(String term : component)
{
term = term.trim();
int coe, exp;
if(term.contains("x")) //check if given term has an exponent and set it as such, otherwise set exp to 0 and omit "x^"
{
String[] parts = term.split("x\\^?");
coe = Integer.parseInt(parts[0]);
exp = (parts.length == 2) ? Integer.parseInt(parts[1]) : 1;
}
else
{
coe = Integer.parseInt(term);
exp = 0;
}
insertionSort(new PolyNode(coe, exp));
}
}
private void insertionSort(PolyNode newNode)
{
if(head == null || newNode.exp > head.exp) //sets the new node as the head if the list is empty or if its exponent is higher than that of the head
{
newNode.next = head;
head = newNode;
}
else //traverses through the list, adding coefficients together if they share an exponent
{
PolyNode current = head;
while(current.next != null && current.next.exp >= newNode.exp)
{
if(current.next.exp == newNode.exp)
{
newNode.coe += current.next.coe;
newNode.next = current.next.next;
current.next.next.prev = newNode;
current.next = newNode;
}
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
}
}
public void print()
{
PolyNode current = head;
StringBuilder result = new StringBuilder();
while(current != null)
{
result.append(current.coe).append("x^").append(current.exp);
if(current.next != null && current.coe < 0)
{
result.append("-");
}
else if(current.next != null && current.coe > 0)
{
result.append("+");
}
current = current.next;
}
System.out.println(result);
}
}
Код: Выделить всё
package polynomialAdder;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner polyScan = new Scanner(System.in);
System.out.println("Enter first polynomial. Please use ^ to indicate exponents");
String polyA = polyScan.nextLine();
PolyList poly1 = new PolyList(polyA);
System.out.println("Enter second polynomial. Please use ^ to indicate exponents");
String polyB = polyScan.nextLine();
PolyList poly2 = new PolyList(polyB);
polyScan.close();
poly1.print();
poly2.print();
}
}
Код: Выделить всё
package polynomialAdder;
public class PolyNode {
int coe;
int exp;
PolyNode next;
PolyNode prev;
PolyNode(int coe, int exp)
{
this.coe = coe;
this.exp = exp;
this.next = null;
this.prev = null;
}
}
Проблема, с которой я столкнулся, заключается в том, что я получаю неверные выходные данные от метода print().
Если я введу, например, «2x^2+3x-4», я получу результат «2x^1», который, как я заметил, привязан к else моего условного оператора, но я не могу понять, почему он дает мне это вывод.
Подробнее: https://stackoverflow.com/questions/799 ... g-properly