1. 题目
2. 代码
这一次的代码我完全没参考其他人的!而且AC得很顺利!(当然,幸好上课发呆的空隙听了一下讲,大概知道思路)
啊哈哈。。。但是代码写的确实不好看,果然还是应该单独判断优先级的。
//(a+b)*c
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main(){
string str;
char tmp;
stack<char> fuhao; //只为符号设置了栈,遇到字母等可以直接输出
cin >> str;
int len = str.length();
for(int i=0; i<len; i++){
switch(str[i]){
case '(':{
fuhao.push(str[i]);
break;
}
case ')':{
while(true){ //将最近的一个左括号前的符号全部输出
tmp = fuhao.top();
fuhao.pop();
if(tmp == '('){
break;
}
else{
cout << tmp;
}
}
break;
}
case '+':
case '-':
{
if(!fuhao.empty() && fuhao.top()!='('){
tmp = fuhao.top();
fuhao.pop();
cout << tmp;
}
fuhao.push(str[i]);
break;
}
case '*':
case '/':{
if(!fuhao.empty()){
tmp = fuhao.top();
if(tmp == '*' || tmp == '/'){
cout << tmp;
fuhao.pop();
}
}
fuhao.push(str[i]);
break;
}
default:{
cout << str[i];
break;
}
}
}
if(!fuhao.empty()){
cout << fuhao.top();
fuhao.pop();
}
return 0;
}
下面用优先级做了一遍,用map键值对存储优先级,代码精简了很多。但是!最开始我把优先级赋值给错了,莫名其妙出现了好些不对的结果。
而且对于 ‘(’ 和 ‘)’ 是不输出的需要注意。很容易这个括号就让人摸不着头脑了。
//a+b*(c-d)-e/f
#include <iostream>
#include <stack>
#include <map>
#include <string>
using namespace std;
int main(int argc, char** argv) {
string str;
cin >> str;
stack<char> fuhao;
fuhao.push('#'); //将#入栈,设置其优先级最高
// 就用map存储优先级
map<char, int> mp = {{')', 1}, {'+', 2}, {'-', 2}, {'*', 3}, {'/', 3}, {'(', 1}, {'#', 0}};
int len = str.length();
char tmp;
for(int i=0; i<len; i++){
if(mp.count(str[i])){ //如果该符号在map中(即属于6种符号之一)
if(!fuhao.empty()){
tmp = fuhao.top();
while(mp[tmp] >= mp[str[i]] && str[i] != '('){
if(tmp != '(' && tmp != ')'){
cout << tmp;
}
// cout << "pop: " << tmp << endl;
fuhao.pop();
tmp = fuhao.top();
}
}
// cout << "push: " << str[i] << endl;
fuhao.push(str[i]);
}
else{ //不属于符号,直接输出
cout << str[i];
}
}
while(!fuhao.empty()){
tmp = fuhao.top();
if(tmp == '#'){
break;
}
if(tmp != '(' && tmp != ')'){
cout << tmp;
}
// cout << "pop: " << endl;
fuhao.pop();
}
return 0;
}