算法:
1.1个栈寄存运算符,1个栈寄存操作数
2.优先级用数组保存好
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<iostream> #include<vector> #include<string> #include<math.h> #include<map> #include<set> #include<stack> #include<algorithm> using namespace std; stack<int>OpE;//操作数栈 stack<char>OpR;//运算符栈 //算符间优先级 int Opet[100]; //栈顶优先权 int Pri[8][8] = {{1,1,-1,-1,-1,1,1}, {1,1,-1,-1,-1,1,1}, {1,1,1,1,-1,1,1}, {1,1,1,1,-1,1,1}, {-1,-1,-1,-1,-1,0,0}, {1,1,1,1,1,1,1}, {-1,-1,-1,-1,-1,-1,-2} }; void init( ) { memset(Opet,0,sizeof(Opet)); Opet['+'] = 0,Opet['-'] = 1,Opet['*'] = 2; Opet['/'] = 3,Opet['('] = 4, Opet[')'] = 5; Opet['#'] = 6; } //判断优先级 int jugde( char p, char q) { return Pri[Opet[p]][Opet[q]]; } int solve(char *str ) { int len = strlen(str), x, y, i = 0, j; char Op = 0, temp[1100]; init( ); OpR.push('#'); bool f = true; str[len] = '#'; while( i <= len && f) { if( str[i] >= '0' && str[i] <= '9' ) //操作数直接入栈 { int ans = 0; for(j = i; j < len; j++) if( str[j] >= '0' && str[j] <= '9' ) temp[ans++] = str[j]; else break; i = j; temp[ans] = '\0'; OpE.push(atoi(temp)); } else { switch( jugde(OpR.top(),str[i]) ) { case 0: OpR.pop();i++;break; case 1: { Op = OpR.top( ); OpR.pop(); x = OpE.top(); OpE.pop(); y = OpE.top( ); OpE.pop( ); if( Op == '+' ) OpE.push( x + y ); else if( Op == '-' ) OpE.push( y - x ); else if( Op == '*' ) OpE.push( y * x ); else if( Op == '/' ) OpE.push( y / x ); break; } case -1: OpR.push(str[i]);i++;break; case -2: f = false;break; } } } return OpE.top(); } int main( ) { char str[1000]; while( scanf("%s",str) != EOF ) { printf("%d\n",solve( str )); } return 0; }