// ======================================================================
// Objetivo: Convertir una expresiOn de infijo a postfijo
// Autor: J. Rafael R. Ochoa
// Fecha: Julio 2004,
// Derechos: SID - FIE - UMSNH
// ======================================================================
import java.util.Stack;
class InfijaAPostfija
{
String EcInf = ""; // Para guardar la ecuaciOn en infijo
Stack Pila = new Stack(); // stack auxiliar como intermediario
InfijaAPostfija(String EcInf) { this.EcInf = EcInf; } // Se recibe la expresiOn en infijo
String Convertir() // inicia la conversiOn
{
String EcPost = ""; // recepciOn de la expresiOn en postfijo
int Indice = 0;
char Symb = ' ', TopSymb = ' ';
String Operando = "", Funcion = "";
while(Indice < EcInf.length())
{
Symb = EcInf.charAt(Indice);
if (EsOperando(Symb))
{
Operando = LeeOperando(EcInf, Indice);
EcPost += Operando + " ";
Indice += Operando.length();
}
else if (EsFuncion(Symb))
{
Funcion = ""+LeeFuncion(EcInf, Indice);
Pila.push((Object)(""+Funcion.charAt(0)));
// EcPost += Funcion + " ";
Indice += Funcion.length();
}
else
{
if (Symb == '(')
Pila.push((Object)(""+Symb));
else
{
while(!Pila.empty() && Precedencia(((String)Pila.peek()).charAt(0), Symb))
{
TopSymb = ((String)Pila.pop()).charAt(0);
EcPost += TopSymb + " ";
}
if (Pila.empty() || Symb != ')')
Pila.push((Object)(""+Symb));
else
{
Pila.pop();
if (!Pila.empty())
if ( EsFuncion(((String)Pila.peek()).charAt(0)))
{
TopSymb = ((String)Pila.pop()).charAt(0);
EcPost += TopSymb + " ";
}
}
}
Indice++;
}
}
// ExtracciOn de operadores restantes.
while (!Pila.empty())
{
TopSymb = ((String)Pila.pop()).charAt(0);
if (TopSymb != '(' && TopSymb != ')')
EcPost += TopSymb + " ";
}
return EcPost;
}
boolean EsFuncion(char Simbolo)
{
// Caracteres que forman las 4 funciones bAsicas
// sen, cos, tan, log base e
// --------------------------------------------------------
if ("sencotalgSENCOTALG".indexOf(Simbolo) >= 0) return true;
return false;
}
String LeeFuncion(String EcInf, int Indice)
{
String Funcion = "";
while( Indice < EcInf.length() && EsFuncion(EcInf.charAt(Indice)) )
{
Funcion += EcInf.charAt(Indice);
Indice++;
}
return Funcion;
}
boolean EsOperando(char Simbolo)
{
if ("0123456789.xX".indexOf(Simbolo) >= 0) return true;
return false;
}
String LeeOperando(String EcInf, int Indice)
{
String Operando = "";
while( Indice < EcInf.length() && EsOperando(EcInf.charAt(Indice)) )
{
Operando += EcInf.charAt(Indice);
Indice++;
}
return Operando;
}
boolean Precedencia(char Opr1, char Opr2)
{
if (Opr1 == '^' && (Opr2 == '*' || Opr2 == '/' || Opr2 == '+' || Opr2 == '-')) return true;
if ((Opr1 == '*' || Opr1 == '/') && (Opr2 == '+' || Opr2 == '-')) return true;
if (Opr1 == '^' && Opr2 == '^') return false;
if (Opr1 == Opr2) return true;
if ((Opr1 == '*' || Opr1 == '/' || Opr1 == '+' || Opr1 == '-' || Opr1 == '^') && Opr2 == ')') return true;
if ((Opr1 == 's' || Opr1 == 'c' || Opr1 == 't') && Opr2 == ')') return true;
return false;
}
}