#include <iostream>
#include <stack>
#include "linkedStackType.h"
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
void evaluarExpresionPostfija(string, linkedStackType < int >&, int &);
string conv_postfija(string &, string &);
int prioridad(char);
bool operador(char operador);
bool operando(char);
int main()
{
string exp_infija, exp_postfija = "";
cout << "INGRESE EXPRESION INFIJA: ";
getline(cin, exp_infija);
conv_postfija(exp_infija, exp_postfija);
cout << "EXPRESION POSTFIJA" << exp_postfija << endl;
int resultado;
linkedStackType <int> enteros;
evaluarExpresionPostfija(exp_postfija, enteros, resultado);
cout << "EL RESULTADO ES : " << resultado << endl;
return 0;
}
void evaluarExpresionPostfija(string expostfija, linkedStackType <int>& stack, int&valor) {
int numero;
stack.initializeStack();
if (!expostfija.empty()) {
while (!expostfija.empty()) {
char indice = expostfija.at(0);
expostfija = expostfija.substr(1, expostfija.length());
string caracter = "";
caracter += indice;
if (operando(indice)) {
numero = atoi(caracter.c_str());
stack.push(numero);
}
if (operador(indice)) {
int op2 = stack.top();
stack.pop();
if (stack.isEmptyStack()) {
cout << "EXPRESION INCORRECTA" << endl;
exit(1);
}
int op1 = stack.top();
stack.pop();
switch (indice) {
case '+': stack.push(op1 + op2);
break;
case '-': stack.push(op1 - op2);
break;
case '*': stack.push(op1*op2);
break;
case '/':
if (op2 != 0)
stack.push(op1 / op2);
else {
cout << "No se puede dividir entre cero" << endl;
exit(1);
}
break;
case '^': stack.push(int(pow(op1, double(op2))));
break;
}
}
}//end while(expostfija.empty())
valor = stack.top();
stack.pop();
}//endif
}
//-----------------------------
string conv_postfija(string&E_inf, string &E_post) {
linkedStackType <char> postfija;
char caracter;
postfija.push('(');
E_inf += ')';
while (!postfija.isEmptyStack()) {
caracter = E_inf.at(0);
E_inf = E_inf.substr(1, E_inf.length());
if (operando(caracter))
E_post += caracter;
if (caracter=='(')
postfija.push(caracter);
if (operador(caracter)) {
if(operador(postfija.top()))
while (prioridad(caracter) <= prioridad(postfija.top())) {
char arg = postfija.top();
E_post += arg;
postfija.pop();
if (!operador(postfija.top()))
break;
}
postfija.push(caracter);
}
if (caracter == ')') {
while (postfija.top() != '(') {
E_post += postfija.top();
postfija.pop();
}//endwhile
return E_post;
}
}
}//endstring
//---------------------------------------------
int prioridad(char oper) {
int prioridad = 0;
if (operador(oper)) {
switch (oper) {
case '^': prioridad = 3;
break;
case '/': prioridad = 2;
break;
case '*': prioridad = 2;
break;
case '+': prioridad = 1;
break;
case '-': prioridad = 1;
break;
}
}
}