c++逆序波兰式求值 | 栈的应用

Question

请编写程序求解10以内的后序波兰式的值

原理:如果读取到数字就入栈,如果读取到字符串就出栈两次,把两个数据进行运算后的结果入栈。过程中注意栈空的情况要及时进行报错,每次运算在第一次top和第二次top的时候都可能会出现这种情况

Example

input
23+6*
output
30

input
23+* //非法的后序表达式
output
none //表示无对应结果

Code

#include <iostream>
#include <stack>
using namespace std;

int main(){
    stack<int>s;
    int p, q;
    char a[100];
    char n;
    bool bl = true;
    scanf("%s", a);

   //开始读取输入的字符串
    int i = 0;
    while (a[i]!='\0')
    {   
        n = a[i];
        if (n >= '0' && n <= '9')
            s.push(n-48);
        else
        {
            if (s.empty()) {
                bl = false;
                cout << "none" << endl;
            }
            else
            {
                p = s.top();
                s.pop();
                if (s.empty()) {
                    bl = false;
                    cout << "none" << endl;
                    s.push(p);
                }
                else
                {
                    q = s.top();
                    s.pop();
                    switch (n)
                    {
                    case '+':
                        p += q;
                        break;
                    case '-':
                        p -= q;
                        break;
                    case '*':
                        p *= q;
                        break;
                    case '/':
                        p /= q;
                        break;
                    }
                    s.push(p);
                }
            }
        }
        i++;
    }
    if(bl)
        cout << s.top() << endl;
    return 0;
}
发布了13 篇原创文章 · 获赞 0 · 访问量 265

猜你喜欢

转载自blog.csdn.net/Caiyii530/article/details/104988144