中缀转后缀表达式||后缀表达书计算

将中缀表达式转换为后缀表达式:
(1) 初始化两个栈:运算符栈S1和储存中间结果的栈S2;
(2) 从左至右扫描中缀表达式;
(3) 遇到操作数时,将其压入S2;
(4) 遇到运算符时,比较其与S1栈顶运算符的优先级:
(4-1) 如果S1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
(4-2) 否则,若优先级比栈顶运算符的高只能是高,相等都不行),也将运算符压入S1;
(4-3) 否则,将S1栈顶的运算符弹出并压入到S2中,再次转到(4-1)与S1中新的栈顶运算符相比较;
(5) 遇到括号时:
(5-1) 如果是左括号“(”,则直接压入S1;
(5-2) 如果是右括号“)”,则依次弹出S1栈顶的运算符,并压入S2,直到遇到左括号为止,此时将这一对括号丢弃;
(6) 重复步骤(2)至(5),直到表达式的最右边;
(7) 将S1中剩余的运算符依次弹出并压入S2;
(8) 依次弹出S2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式(转换为前缀表达式时不用逆序)。

string fun(string &s)
{
    string res;
    stack<char> st;
    auto it = s.begin();
    while (it != s.end())               //按优先级别入栈,如果当前优先级比栈顶优先级高,才入栈,
                                       //比栈顶小或相同,则栈顶出栈(一直到栈顶符合比当前元素优先级低)当前元素入栈。
    {

        if (*it >= '0'&&*it <= '9')
            res += *it;
        else if (*it == '+' || *it == '-')    //+ -的优先级最低,所以他下面的都要出栈(除了括号)
        {
            while (!st.empty()&&(st.top() != '('|| st.top() == ')'))   
            {
                    res += st.top();
                    st.pop();
            }
            st.push(*it);
        }
        else if (*it == '*' || *it == '/')   //* /的优先级只会比+ -的高,所以下面是*或者/都要出栈
        {
            while (!st.empty() && (st.top() == '*' || st.top() == '/'))
            {
                res += st.top();
                st.pop();
            }
            st.push(*it);
        }
        else if (*it == '(')           //括号单独考虑 左括号直接入栈 右括号直接出栈致左括号
            st.push(*it);
        else if (*it == ')')
        {
            while (st.top()!='(')
            {
                res += st.top();
                st.pop();
            }
            st.pop();

        }
        it++;
    }
    while (!st.empty())
    {
        res += st.top();
        st.pop();
    }
    return res;
}
int calc(string &s)         //计算后缀表达式,遇到符号前俩数运算
{

    stack<int> st;
    auto it = s.begin();
    while (it != s.end())
    {
        if (*it >= '0'&&*it <= '9')
            st.push(*it-'0');
        else
        {
            int tmp1 = st.top();
            st.pop();
            int tmp2 = st.top();
            st.pop();
            if (*it == '+')
                st.push(tmp1 + tmp2);
            else if (*it == '-')
                st.push(tmp2 - tmp1);
            else if(*it == '*')
                st.push(tmp2 * tmp1);
            else
                st.push(tmp2 / tmp1);
        }
        ++it;

    }
    return st.top();

}
int _tmain(int argc, _TCHAR* argv[])
{
    /*string s = "9+(3-1)*3+4/2";*/
      string s = "(3+4)*5-6*1-8/(2+2/1)"; 
    //string s = "1+((2+3)*4)-5";
    string res = fun(s);
    cout << res << endl;
    cout << calc(res) << endl;
    return 0;
}
点赞