#include <iostream>
#include <string>
#include <cctype>
#include <stack>
using namespace std;
int main()
{
string postfix(string);
int toInt(string); //将string类字符串转换成整数
int calculate(string); //用后缀表达式计算
string infixExp;
cout<<"提示:输入“#”停止\n";
for(;;)
{
cout<<"\n中缀表达式为:";
cin>>infixExp;
if(infixExp=="#") break;
cout<<"后缀表达式为: "<<postfix(infixExp)<<endl;
cout<<"计算值为: "<<calculate(postfix(infixExp))<<endl;
}
return 0;
}
string postfix(string exp)
{
char token,topToken;
stack <char> opStack;
string postfixExp;
const string BLANK=" ";
for(int i=0;i<exp.length();i++)
{
token=exp[i];
switch(token)
{
case ' ': break;
case '(': opStack.push(token);
break;
case ')': while(!opStack.empty())
{
topToken=opStack.top();
opStack.pop();
if(topToken=='(') break;
postfixExp.append(BLANK + topToken);
}
break;
case '+':
case '-':
case '*':
case '/':
case '%': for(;;)
{
if(opStack.empty() ||
opStack.top()=='(' ||
((token=='*' || token=='/' || token=='%') &&
(opStack.top()=='+' || opStack.top()=='-')))
{
opStack.push(token);
break;
}
else
{
topToken=opStack.top();
opStack.pop();
postfixExp.append(BLANK + topToken);
}
}
break;
default: postfixExp.append(BLANK + token);
for(;;)
{
if(!isalnum(exp[i+1])) break;
i++;
token=exp[i];
postfixExp.append(1,token);
}
}
}
for(;;)
{
if(opStack.empty()) break;
topToken=opStack.top();
opStack.pop();
if(topToken!='(')
{
postfixExp.append(BLANK + topToken);
}
else
{
cout<<"*** 中缀表达式错误 ***\n";
break;
}
}
return postfixExp;
}
int toInt(string s)
{
int num=0;
int n=int(s.size());
for(int i=0;i<n;i++)
{
int a=int(s[i])-48;
num=num*10+a;
}
return num;
}
int calculate(string exp)
{
char token;
int n1,n2;
stack <int> s;
for(int i=0;i<exp.length();i++)
{
token=exp[i];
switch(token)
{
case ' ': break;
case '+':
n1=s.top();
s.pop();
n2=s.top();
s.pop();
s.push(n1+n2);
break;
case '-':
n1=s.top();
s.pop();
n2=s.top();
s.pop();
s.push(n1-n2);
break;
case '*':
n1=s.top();
s.pop();
n2=s.top();
s.pop();
s.push(n1*n2);
break;
case '/':
n1=s.top();
s.pop();
n2=s.top();
s.pop();
s.push(n1/n2);
break;
case '%':
n1=s.top();
s.pop();
n2=s.top();
s.pop();
s.push(n1%n2);
break;
default:
string temp="";
for(;;)
{
temp=temp+token;
if(!isalnum(exp[i+1])) break;
i++;
token=exp[i];
}
s.push(toInt(temp));
}
}
return s.top();
}
数据结构:中缀表达式转后缀表达式
猜你喜欢
转载自blog.csdn.net/qq_41579622/article/details/81632112
今日推荐
周排行