3.表达式:
原题链接:102633.3.表达式2026-02-04 14:57:00
发布于:江苏
**中缀表达式转前缀表达式**:
const int maxSize = 109;
//判断运算符的优先级
int getPriority(char op) {
if (op == '+' || op == '-')
return 0; //+或-的优先级比较低
else
return 1;
}
void infixToPreFix(char infix[], int len, stack<char>& s2) {
stack<char> s1;//符号栈
int i = len - 1;
while (i >= 0) {
if ('a' <= infix[i] && infix[i] <= 'z') {
s2.push(infix[i]);
--i;
} else if (infix[i] == ')') {
s1.push(infix[i]);
--i;
} else if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/') {
if (s1.size() == 0 || s1.top() == ')' || getPriority(infix[i]) >= getPriority(s1.top())) {
s1.push(infix[i]);
--i;
} else {
s2.push(s1.top());
s1.pop();
}
}
if (infix[i] == '(') {
while (s1.top() != ')') {
s2.push(s1.top());
s1.pop();
}
s1.pop();
--i;
}
}
while (s1.size()) {
s2.push(s1.top());
s1.pop();
}
}
char s[109];
stack<char> res;
int main() {
cin >> s;
int len = -1;
infixToPreFix(s, strlen(s), res);
while (res.size()) {
cout << res.top();
res.pop();
}
** 中缀表达式转后缀表达式**:
stack<char>s;
char ans[109],str[109];
int idx=0;
int level(char s) {
if(s=='+'||s=='-')return 1;
else if(s=='*'||s=='/')return 2;
}
int main() {
cin>>str;
for(int i=0; str[i]!='\0'; i++) {
if(str[i]>='a'&&str[i]<='z')
ans[idx++]=str[i];
else if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/') {
if(s.empty()||level(str[i])>level(s.top())) {
s.push(str[i]);
} else {
while(!s.empty()&&level(s.top())>=level(str[i])) {
if(s.top()=='(') break;
ans[idx++]=s.top();
s.pop();
}
s.push(str[i]);
}
} else { //界限符
if(str[i]=='(')s.push(str[i]);
else if(str[i]==')') {
while(s.top()!='(') {
ans[idx++]=s.top();
s.pop();
}
s.pop();
}
}
}
while(!s.empty()) {
ans[idx++]=s.top();
s.pop();
}
cout<<ans;
**前缀表达式求值**:
string s;
cin >> s;
stack<int> st;
for (int i = s.length()-1; i >= 0; i--) {
if (s[i] >= '0' && s[i] <= '9') {
st.push(s[i] - '0');
} else {
int l = st.top();
st.pop();
int r = st.top();
st.pop();
if (s[i] == '+') {
st.push(l + r);
} else if (s[i] == '-') {
st.push(l - r);
} else if (s[i] == '*') {
st.push(l * r);
} else if (s[i] == '/') {
st.push(l / r);
}
}
}
cout << st.top();
**后缀表达式求值**:
string s;
cin>>s;
stack<int> num;
for(int i=0;i<s.size();i++){
if(s[i]>='0' && s[i]<='9'){
num.push(s[i]-48);
}
else{
int r=num.top(); num.pop();
int l=num.top(); num.pop();
if(s[i]=='+') num.push(l+r);
else if(s[i]=='-') num.push(l-r);
else if(s[i]=='*') num.push(l*r);
else num.push(l/r);
}
}
cout<<num.top();
这里空空如也





















有帮助,赞一个