栈进阶—3 后缀表达式求值
AC代码:
#include<iostream>
#include<stack>
using namespace std;
stack<int> st;//存储运算过程中的数字
string s;
int main(){
while(cin>>s){
if(s=="@")break;
if(isdigit(s[0])){//当前字符串是数字
int x=stoi(s);//将字符串s转换为数字
st.push(x);//将数字进栈
}else{//是运算符
int b=st.top();st.pop();//弹出栈顶元素作为第二个操作数
int a=st.top();st.pop();//弹出栈顶元素作为第一个操作数
//根据运算符进行相应计算,并将结果压入栈中
if(s=="+")st.push(a+b);
else if(s=="-")st.push(a-b);
else if(s=="*")st.push(a*b);
else if(s=="/")st.push(a/b);
}
}
printf("%d",st.top());//输出表达式计算结果
return 0;
}总结:使用栈计算后缀表达式,遇到数字入栈,遇到运算符则弹出两栈顶元素进行运算,然后将结果入栈
U445233 栈进阶—5 表达式求值
AC代码:
#include<iostream>
#include<stack>
using namespace std;
stack<long long> st;//存储中间计算结果
char c;//读取运算符
long long a,sum;//a:读取数字,sum:存储最终结果
int main(){
cin>>a;
st.push(a%10000);
while(cin>>c>>a){
if(c=='+')st.push(a%10000);//如果是加法运算符,直接将数字对10000取模后压入栈
else if(c=='*'){//如果是乘法运算符
int x=st.top()%10000;//取出栈顶元素并取模
st.pop();
st.push((x*a)%10000);//将乘积对10000取模后压入栈
}
}
while(st.size()){//计算栈中所有元素的和
sum+=st.top();sum=sum%10000;st.pop();//取出栈顶元素加到最终结果中
}
cout<<sum%10000;//只输出最后4位
return 0;
}总结:用栈处理表达式,注意结果只保留末四位
栈进阶—6 中缀转后缀表达式
AC代码:
#include<iostream>
#include<stack>
#include<map>
using namespace std;
stack<char> s;//存储运算符
map<char,int> mp;//存储运算符优先级
string str;
int main(){
mp['(']=0;mp['+']=1;mp['-']=1;mp['*']=2;mp['/']=2;//初始化运算符的优先级
cin>>str;
for(int i=0;i<str.size();++i){
if(str[i]>='a'&&str[i]<='z')cout<<str[i];//遇到字母直接输出
else{
if(str[i]=='(')s.push(str[i]);//遇到左括号,压入栈中
else if(str[i]==')'){//遇到右括号
while(s.top()!='('){//弹出栈顶元素并输出,直到遇到左括号
cout<<s.top();
s.pop();
}
s.pop();//弹出左括号但不输出
}else{//遇到运算符
while(s.size()!=0&&mp[str[i]]<=mp[s.top()]){
cout<<s.top();
s.pop();
if(s.empty())break;//栈为空时跳出循环
}
s.push(str[i]);//将当前运算符压入栈中
}
}
}
while(s.empty()!=1){//将栈中剩余的运算符全部输出
cout<<s.top();
s.pop();
}
return 0;
}总结:重点在于处理运算符优先级和括号匹配