#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <cstring>
using namespace std;
int youXianJi(char a){ //字符判断优先级
int k;
switch(a){
case'+': case'-': k = 1; break;
case'*': case'/': k = 2; break;
case'#': k = 0; break;
}
return k;
}
int jisuan(int a,int b,char c){
switch(c){ //确定四则运算
case'+': return a+b;break;
case'-': return a-b;break;
case'*': return a*b;break;
case'/': return a/b;break;
default: break;
}
}
int qiuZhi(char s[]){
stack<char> s1,s2,s3; //s1暂定存储数字栈,s2暂定存储符号栈,s3转换后的后缀表达式
stack<int> s4; //后缀表达式运算的数字存储栈
s2.push('#');
for(int i = 0;i<strlen(s);i++){
if(s[i]>='0'&&s[i]<='9'){
s1.push(s[i]); //数据段压入
}
if(s[i]=='('){ //左单括号直接压入s2暂定符号栈
s2.push('(');
}
if(s[i]==')'){
while(s2.top()!='('){
char c = s2.top();
s1.push(c);
s2.pop();
}
s2.pop(); //注意:将左单括号弹出
}
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){ //(+,-,*,/)要与暂定符号栈s2栈顶元素对比优先级
if(s2.top()=='('){
s2.push(s[i]);
}
else{
while(true){ //循环到s[i]优先级大于暂定符号栈s2的栈顶元素,并将s[i]压入s2
if(youXianJi(s[i])<=youXianJi(s2.top())){
char item = s2.top();
s1.push(item);
s2.pop();
}
else{
s2.push(s[i]);
break;
}
}
}
}
}
while(s2.top()!='#'){ //将暂定符号栈s2中全部元素压入s1,得到的s1为后缀表达式的逆序
s1.push(s2.top());
s2.pop();
}
while(!s1.empty()){ //s1逆序得到s3;s3为表达式的最终后缀表达式
s3.push(s1.top());
s1.pop();
}
while(!s3.empty()){ //s4为最终数字存储栈
if('0'<=s3.top()&&s3.top()<='9'){
s4.push(s3.top()-'0');
s3.pop();
}
else{
int a = s4.top();
s4.pop();
int b = s4.top();
s4.pop();
int c = jisuan(b,a,s3.top());
s3.pop();
s4.push(c);
}
}
return s4.top();
}
int main(int argc, char** argv) {
char s[20];
printf("输入中缀表达式:\n");
scanf("%s",s);
for(int i = 0;i<strlen(s);i++){
printf("%c",s[i]);
}
printf("=%d\n",qiuZhi(s));
return 0;
}
栈实现中缀表达式的值
最新推荐文章于 2023-02-17 16:35:30 发布