完成以上步骤,S2栈便为逆波兰式输出结果。
#include <cstdio> #include <cstring> #include <algorithm> #include <stack> #include <ctype.h> using namespace std; const int N = 5000; char str[N]; char ans[N]; int map[256]; bool isOper(char ch) { if(ch == '+' || ch == '-' || ch == '*' || ch == '/') { return true; } return false; } void init() { memset(map,0,sizeof(map)); map['#'] = -1;map['('] = 0; map['+'] = 1;map['-'] = 1; map['*'] = 2;map['/'] = 2; } int main() { int t; init(); scanf("%d",&t); getchar(); getchar(); while(t--) { char tmp[N]; int len = 0; while(gets(tmp)) { if(tmp[0] == '\0'){ break; } str[len++] = tmp[0]; } str[len++] = '#'; str[len++] = '\0'; stack<char> op; //运算符栈 op.push('#'); int cnt = 0; for(int i = 0; i < len; i++) { if(str[i] == '(') { op.push(str[i]); }else if(str[i] == ')') { while( op.top() != '(') { ans[cnt++] = op.top(); op.pop(); } op.pop(); }else if(isdigit(str[i])) { //如果是操作数,则直接进入后缀子 ans[cnt++] = str[i]; }else if(str[i] == '#') { //如果当前为'#',则弹出所有 while(op.top() != '#') { ans[cnt++] = op.top(); op.pop(); } }else if(isOper(str[i])) { //若当前字符为运算符且优先级大于栈顶运算符,则进栈, //否则退出栈顶运算符并将其发送给后缀式。然后将当前运算符放入栈中。 while(map[str[i]] <= map[op.top()]) { ans[cnt++] = op.top(); op.pop(); } op.push(str[i]); } } ans[cnt++] = '\0'; printf("%s\n",ans); if(t) { printf("\n"); } } return 0; }