C++算法8:逆波兰表达式的计算

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuan_zizizi/article/details/81909564

1.计算方法:当前字符为操作数,则压栈;若当前字符是操作符,则弹出栈中的两个操作数,计算后压栈。
2.代码
(1)不输入字符串

# include<iostream>
# include<stack>
# include<stdlib.h>
# include<string>
using namespace std;

# include<iostream>
# include<stack>
# include<stdlib.h>
using namespace std;

//声明
bool IsOpreator(const char *op);
int ReversePoli(const char *str[], int len);
//判断是否操作符
bool IsOpreator(const char *op)
{
    return ((op[0] == '+') || (op[0] == '-') || (op[0] == '*') || (op[0] == '/'));
}

//定义逆波兰表达式
int ReversePoli(const char *str[], int len)
{
    int a, b;
    const char *p;
    stack<int> s;
    for (int i = 0; i < len; i++)
    {
        p = str[i];
        if (!IsOpreator(p))
        {
            s.push(atoi(p));
        }
        else
        {
            a = s.top();
            s.pop();
            b = s.top();
            s.pop();
            if (p[0] == '+')
                s.push(a + b);
            if (p[0] == '-')
                s.push(a - b);
            if (p[0] == '*')
                s.push(a * b);
            if (p[0] == '*')
                s.push(a * b);
            if (p[0] == '/')
                s.push(a / b);
        }
    }
    return s.top();
}

int main()
{
    const char *str[] = { "2","1","+","3","*" };
    int len = sizeof(str)/sizeof(const char*);
    int result = ReversePoli(str, len);
    cout << result << endl;
}

(2)带字符串输入

# include<iostream>
# include<stack>
# include<stdlib.h>
# include<string>
using namespace std;


//声明
bool IsOpreator(char op);
int ReversePoli(char str[], int len);
//判断是否操作符
bool IsOpreator(char op)
{
    return ((op == '+') || (op == '-') || (op == '*') || (op == '/'));
}

//定义逆波兰表达式
int ReversePoli(char str[], int len)
{
    int a, b;
    char p;
    stack<int> s;
    for (int i = 0; i < len; i++)
    {
        p = str[i];
        if (!IsOpreator(p))
        {
            s.push(p - '0');
        }
        else
        {
            a = s.top();
            cout << a << endl;
            s.pop();
            b = s.top();
            cout << b << endl;
            s.pop();
            if (p == '+')
            {
                s.push(a + b);
            }
            if (p == '-')
                s.push(a - b);
            if (p == '*')
                s.push(a * b);
            if (p == '*')
                s.push(a * b);
            if (p == '/')
                s.push(a / b);
        }
    }
    return s.top();
}

int main()
{
    char str[1000];
    cin >> str;
    char *s = str;
    long len = strlen(str);
    long long result = ReversePoli(s, len);
    cout << result << endl;
}

3.结果:

9
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/xuan_zizizi/article/details/81909564