📜  使用堆栈的前缀 - C++ 代码示例

📅  最后修改于: 2022-03-11 14:44:54.169000             🧑  作者: Mango

代码示例1
#include
#include
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:   ." << endl;
    string exp;
    cout << "\nEnter Prefix Expression: ";
    cin >> exp;
    int result = EvaluatePrefix(exp);
    cout << "\nResult = " << result << endl;

    return 0;
}
//
int EvaluatePrefix(string exp)
{
    stack 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;
}