中缀表达式
就是普通人们最常用的加减乘除式子
(或中缀记法)是一个通用的算术或逻辑公式表示方法, 操作符是以中缀形式处于操作数的中间(例:3 + 4),中缀表达式是人们常用的算术表示方法。
与q前缀表达式(例:+ 3 4)或h后缀表达式(例:3 4 +)相比,中缀表达式不容易被计算机解析,但仍被许多程序语言使用,因为它符合人们的普遍用法。
与前缀或后缀记法不同的是,中缀记法中括号是必需的。计算过程中必须用括号将操作符和对应的操作数括起来,用于指示运算的次序。
后缀表达式
运算符在运算数后面,从左到右进行运算
中缀转后缀
如遇数字直接输出,若遇左括号直接入栈,若遇右括号则持续输出栈中内容直到遇到左括号为止(左右括号均不输出仅需在栈中删除)若遇到操作符需持续输出栈中内容直到遇到比当前操作符的优先级低的为止再将该操作符压入栈中,最后读到末尾将栈中所有内容输出即可。
第一种将优先级直接带入到里面(好理解)
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string s;
cin >> s;
stack<char> o;
for(int i=0; i<s.size(); i++)
{
if(s[i]>='0'&&s[i]<='9') cout << s[i];
else
{
if(o.empty()) o.push(s[i]);
else if(s[i]=='+'||s[i]=='-')
{
while(o.top()!='(')//只有左括号优先级小于+-
{
cout << o.top();
o.pop();
if(o.empty()) break;
}
o.push(s[i]);
}
else if(s[i]=='*'||s[i]=='/')
{
while(o.top()=='*'||o.top()=='/')//不是*/的话就是优先级小于了,就可以进栈了
{
cout << o.top();
o.pop();
if(o.empty()) break;
}
o.push(s[i]);
}
else if(s[i]=='(') o.push(s[i]);
else if(s[i]==')')
{
while(o.top()!='(')//将栈中两括号之间的全部输出
{
cout << o.top();
o.pop();
}
o.pop();//删去括号
}
}
}
while(!o.empty())
{
cout << o.top();
o.pop();
}
}
第二种先将优先级列出来
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int isp(char c)
{
if(c == '#')
{
return 0;
}
else if(c == '(')
{
return 1;
}
else if(c == '+' || c == '-')
{
return 3;
}
else if(c == '*' || c == '/')
{
return 5;
}
else if(c == ')')
{
return 6;
}
}
int icp(char c)
{
if(c == '#')
{
return 0;
}
else if(c == '(')
{
return 6;
}
else if(c == '+' || c == '-')
{
return 2;
}
else if(c == '*' || c == '/')
{
return 4;
}
else if(c == ')')
{
return 1;
}
}
int main()
{
string s;
cin >> s;
stack<char> p;
stack<char> o;
o.push('#');
s+='#';
int index=0;
while(index<s.size())
{
if(s[index]>='0'&&s[index]<='9')
{
p.push(s[index]);
cout << p.top();
p.pop();
index++;
}
else
{
if(icp(s[index])==isp(o.top()))
{
o.pop();
index++;
}
else if(icp(s[index])>isp(o.top()))
{
o.push(s[index]);
index++;
}
else
{
if(o.top()==')') o.pop();
else
{
cout << o.top();
o.pop();
}
}
}
}
}