awalan menggunakan tumpukan
#include<iostream>
#include<stack>
using namespace std;
int EvaluatePrefix(string exp);
bool IsNumber(char ch);
bool IsOperator(char ch);
int PerformOperation(char ch, int op1, int op2);
int main()
{
cout << "Prefix form: <operator> <operand> <operand>." << endl;
string exp;
cout << "\nEnter Prefix Expression: ";
cin >> exp;
int result = EvaluatePrefix(exp);
cout << "\nResult = " << result << endl;
return 0;
}
//
int EvaluatePrefix(string exp)
{
stack<char> s;
for (int i = exp.length(); i >= 0; i--)
{
if (IsNumber(exp[i]))
{
s.push(exp[i]-'0');
}
else if (IsOperator(exp[i]))
{
int op1 = s.top(); s.pop();
int op2 = s.top(); s.pop();
int result = PerformOperation(exp[i],op1,op2);
s.push(result);
}
}
return s.top();
}
//
bool IsNumber(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
//
bool IsOperator(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
return true;
return false;
}
//
int PerformOperation(char ch, int op1, int op2)
{
if (ch == '+') return op1 + op2;
else if (ch == '-') return op1 - op2;
else if (ch == '*') return op1 * op2;
else if (ch == '/') return op1 / op2;
else return -1;
}
coder