栈实现计算式
map是哈希方式,可以改为函数形式,就是传入“+”,“-”返回1,*,/返回2,( 返回 0就行。
点击查看代码
#include<iostream>
#include <map>
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;
map<char, int> prior = { {'+',1},{'-',1},{'*',2},{'/',2},{'(',0} }; //哈希存储
ll res;
char ch[N];
struct s {
ll shu[N];
int top=0;
}Shi;
struct c {
char ch[N];
int topc=0;
}Chr;
ll topp1() { //弹出数字栈的一个数字
return Shi.shu[Shi.top-1];
}
char topp2() {//弹出运算符栈的第一个运算符
return Chr.ch[Chr.topc-1];
}
void push1(int x) {//将x加入数字栈
Shi.shu[Shi.top] = x; Shi.top++;
}
void push2(char x) {//将字符x加入字符栈
Chr.ch[Chr.topc] = x; Chr.topc++;
}
void pop(int& p) {//删除栈头
p--;
}
void cal(){//运算数字栈的两个数字,并将其再次插入数字栈
ll b = topp1(); Shi.top--;
ll a = topp1(); Shi.top--;
char c = topp2(); Chr.topc--;
ll res = 0;
if (c == '+') res = a + b;
else if (c == '-') res = a - b;
else if (c == '*') res = a * b;
else if (c == '/') res = a / b;
push1(res);
}
int main(){
string f;
cout << "请输入你的计算式:\n";
cin >> f;
for (int i = 0; i < f.size(); i++){//遍历字符串
int sum = 0;
if (f[i] >= '0' && f[i] <= '9'){
while (i < f.size() && f[i] >= '0' && f[i] <= '9'){//记录数字,直至遇到运算符
sum = sum * 10 + f[i] - '0';
i++;
}
i--;
push1(sum);//加入栈,记录数字
}
else{ //当其是运算符时,分情况判断
if (f[i] == '(')
push2(f[i]);
else if (f[i] == ')'){
while (topp2() != '(')/*遇到右括号就向前面找左括号配对,将其中的算式全部计算,因为后面将乘除都计算了,所以不用考虑计算优先级*/
cal();
Chr.topc--;
}
else{
while (Chr.topc > 0 && prior[f[i]] <= prior[topp2()])/*优先级高的就直接计算,(加减前面运算都可以进行至括号处,乘除运算至加减处)*/
cal();
push2(f[i]);
}
}
}
while (Chr.topc > 0)//将剩余的算式全部计算
cal();
printf("%lld\n", topp1());
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话