1.后缀表达式计算值
#include <iostream>
#include <stack>
#include <iomanip>
using namespace std;
double cal(string s){
stack<double> stk;
int len = s.size();
for(int i=0;i<len;i++){
if(!(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')){
stk.push(s[i]-'a'+1);
}
else{
double a = stk.top();
stk.pop();
double b = stk.top();
stk.pop();
if(s[i] == '+'){
stk.push(a+b);
}
else if(s[i] == '-'){
stk.push(b-a);
}
else if(s[i] == '*'){
stk.push(a*b);
}
else{
stk.push(b/a);
}
}
}
return stk.top();
}
int main(){
int t;
cin>>t;
while(t--){
string s;
cin>>s;
cout<<fixed<<setprecision(2)<<cal(s)<<endl;
}
return 0;
}
2. 中缀表达式转化为后缀表达式
#include <iostream>
#include <stack>
using namespace std;
bool prior(char stacktop,char input){
switch(stacktop){
case '+':
case '-':
switch(input){
case '*':
case '/':
return true;
break;
}
}
return false;
}
string infixTopostfix(string infix){
string postfix = "";
stack<char> stk;
int len = infix.size();
for(int i=0;i<len;i++){
if(infix[i] == '('){
stk.push(infix[i]);
}
else if(infix[i] == ')'){
while(stk.top() != '(' && !stk.empty()){
postfix += stk.top();
stk.pop();
}
stk.pop();
}
else if(infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/'){
while(!stk.empty() && stk.top() != '(' && !prior(stk.top(),infix[i])){
postfix += stk.top();
stk.pop();
}
stk.push(infix[i]);
}
else postfix += infix[i];
}
while(!stk.empty()){
postfix += stk.top();
stk.pop();
}
return postfix;
}
int main(){
int t;
cin>>t;
while(t--){
string s;
cin>>s;
cout<<infixTopostfix(s)<<endl;
}
return 0;
}
3. 括号匹配
#include <iostream>
#include <stack>
using namespace std;
bool f(string s){
stack<char> stk;
int len = s.size();
for(int i=0;i<len;i++){
if(!(s[i] == '(' || s[i] == '[' || s[i] == '{' ||
s[i] == ')' || s[i] == ']' || s[i] == '}' )){
continue;
}
else if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
stk.push(s[i]);
}
else if(s[i] == ')'){
if(stk.empty()){
return false;
}
else if(stk.top() == '('){
stk.pop();
continue;
}
else return false;
}
else if(s[i] == ']'){
if(stk.empty()){
return false;
}
else if(stk.top() == '['){
stk.pop();
continue;
}
else return false;
}
else if(s[i] == '}'){
if(stk.empty()){
return false;
}
else if(stk.top() == '{'){
stk.pop();
continue;
}
else return false;
}
}
if(!stk.empty()) return false;//坑~~忽略可能剩下’(‘的情况了
return true;
}
int main(){
int t;
cin>>t;
while(t--){
string s;
cin>>s;
if(f(s)){
cout<<"Yes"<<endl;
}
else cout<<"No"<<endl;
}
return 0;
}