我的程序应该接收一个等式(ex: x^4*(x+3)),并将其转换为post顺序(或反向波兰符号),然后我需要创建一棵需要放入堆栈中的树。棘手的部分是阅读后序方程。在这个例子中,应该是:
X4^x3+*
所以做树的规则是:
如果是二进制操作("+“、"-”、"^“、"/”、"*"),则应该接受堆栈的前2个元素,创建一个以操作为根的树,并将数字作为其子项,并将其推入堆栈中。
如果它是一个一元操作("&“表示ln,"~”表示负(~3)=(-3)),它应该以堆栈的第一个元素为基础,创建一个以操作为根的树,并将其作为其子元素,并将其推入堆栈中。
如果是数字或字母,则应该创建一个没有子节点,并将其推入堆栈。
我检测字符串中的字母、二进制或一元操作的算法是:(已经创建了Post方程,它是由我的老师发送的,因此没有什么可编辑的)
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="";
}
}然后创建Stack:
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);
}
}我的问题是,它没有检测它是否是二进制操作。它马上就会转到其他地方。我打印了霍尔,全息和海莱,看看元素的去向,但我得到的只是海莱。
x
hele4
hele^
helex
hele3
hele+
hele*我真的不知道它为什么要跳过其他的Ifs,是二进制操作还是一元。以防万一,这是树类
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;
}
}我会很感激你能给我的一切帮助。
发布于 2015-04-24 03:26:09
在检测操作符时,您使用==来比较应该使用.equals的字符串。
https://stackoverflow.com/questions/29838135
复制相似问题