stack(括号,表达式)

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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值