VJ_Transform the Expression_stack

//
Transform the algebraic expression with brackets into RPN form (Reverse Polish Notation).
 Two-argument operators: +, -, *, /, ^ (priority from the lowest to the highest), brackets ( ). 
Operands: only letters: a,b,...,z. Assume that there is only one RPN form (no expressions like a*b*c).

Input
t [the number of expressions <= 100]
expression [length <= 400]
[other expressions]
Text grouped in [ ] does not appear in the input file.

Output
The expressions in RPN form, one per line.
Example
Input:
3
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))

Output:
abc*+
ab+zx+*
at+bac++cd+^*

//
#include<bits/stdc++.h>
using namespace std;

stack<char> sk;

int main()
{
    string s;           // 找规律 可以发现 只是将运算符后置而已
    int n,i;            // 再稍微观察一下 其实就是遇上 右括号 就出栈

    while( cin>>n )
    {
        cin.get();
        while( n-- )
        {
            while( !sk.empty() ) sk.pop();

            getline( cin,s );
            for( i=0;i<s.size();i++ )
            {
                if( s[i]=='(' ) continue;

                if( isalpha( s[i] ) ) 
                                cout<<s[i];
                else if( s[i]==')' ) 
                                { cout<<sk.top(); sk.pop(); }
                else 
                                sk.push( s[i] );
            }
            cout<<endl;
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_63173957/article/details/124473802