我的程序应该接收一个等式(例如:x^4*(x+3))并将其转换为后序(或反向波兰表示法),之后我需要创建一棵需要放置的树在一个堆栈中。棘手的部分是通读后序方程。在示例中它应该是:
x 4 ^ x 3 + *
所以关于造树的规则是:
如果它是二元操作 ("+","-","^","/","*") 它应该取堆栈的前 2 个元素,创建一个以该操作为根的树,和数字作为它的儿子,并将其压入堆栈。
如果是一元运算("&"代表ln,"~"代表负数(~3)=(-3)),它应该取栈的第一个元素,用操作创建一棵树作为根,数字作为它的儿子,并将其压入堆栈。
如果是数字或者字母,应该创建一个没有儿子的节点,直接压入栈即可。
我通过字符串检测它是字母、二进制还是一元运算的算法是: (后序方程已经创建,它是我的老师发送的,所以那里没有什么可以编辑的)
String aux="";
for (int i=0; i < nuevaF.length();i++){
char c = nuevaF.charAt(i);
if (c!=' '){
aux=aux+c;
System.out.println(aux);
}
if (c==' '){
System.out.println("space");
Transformar(stack,aux);
aux="";
}
}
然后创建堆栈:
public static void Transformar(PilaArreglo stack, String ecuacion){
if (ecuacion=="+"||ecuacion=="-"||ecuacion=="*"||ecuacion=="/"||ecuacion=="^"){
Nodo aux1 = stack.desapilar();
Nodo aux2 = stack.desapilar();
Nodo total = new Nodo(ecuacion,aux2, aux1);
System.out.println("hole");
stack.apilar(total);
}
else if (ecuacion=="&"||ecuacion=="~"){
Nodo aux1 =stack.desapilar();
Nodo total2 = new Nodo(ecuacion,aux1);
System.out.println("holo");
stack.apilar(total2);
}
else{
Nodo total3 = new Nodo(ecuacion);
System.out.print("hele");
stack.apilar(total3);
}
}
我的问题是它没有检测它是否是二元运算。它立即转到其他地方。我打印 Hole、holo 和 hele 以查看元素的去向,但我得到的只是 hele。
x
hele4
hele^
helex
hele3
hele+
hele*
我真的不知道为什么它会跳过其他 If,如果它是二元运算或一元运算。 为了以防万一,这里是 Tree 类
public class Nodo{
Object element;
Nodo izq;
Nodo der;
Nodo(String x, Nodo y, Nodo z){
element = x;
izq = y;
der = z;
}
Nodo(String x, Nodo y){
element = x;
izq = y;
der = null;
}
Nodo(String x){
element = x;
izq = null;
der = null;
}
}
还有堆栈(应该是一堆节点)
class PilaArreglo{
private Nodo[] arreglo;
private int tope;
private int MAX_ELEM=100; // max numbers on stack
public PilaArreglo(){
arreglo=new Nodo[MAX_ELEM];
tope=-1; // empty stack
}
public void apilar(Nodo x){
if (tope+1<MAX_ELEM){ // if full, OVERFLOW
tope++;
arreglo[tope]=x;
}
else{
MAX_ELEM=MAX_ELEM*2;
Nodo[] nuevo_arreglo=new Nodo[MAX_ELEM];
for (int i=0; i<arreglo.length; i++){
nuevo_arreglo[i]=arreglo[i];
}
tope++;
nuevo_arreglo[tope]=x;
arreglo=nuevo_arreglo;
}
}
public Nodo desapilar(){
if (!estaVacia()){ // si esta vacia se produce UNDERFLOW
Nodo x=arreglo[tope];
tope--;
return x;
}
return null;
}
public Nodo tope(){
if (!estaVacia()){ // si esta vacia es un error
Nodo x=arreglo[tope];
return x;
}
return null;
}
public boolean estaVacia(){
if (tope==-1)
{
return true;
}
else
{
return false;
}
}
我会感谢你能给我的每一个帮助。
最佳答案
您正在使用 ==
来比较字符串,而在检测运算符时您应该使用 .equals
。
关于java - 一堆树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838135/