LISP~~~~~

#include<iostream>

#include<vector>

#include<stack>

#include<string>

using namespace std;

void Lisp(string str)

{

vector<string> st;

stack<int>res;

bool flag = true;

int n = str.size();

for(int i = n - 1; i >= 0;)

{

if(str[i] == ')' || str[i] == ' ' || str[i] == '(')

{

i--;

}

else if(str[i] >= 'a' && str[i] <= 'z')

{

string op = str.substr(i - 2, 3);

st.push_back(op);

i -= 3;

}

else

{

int spaceIndex = str.rfind(' ', i);

string num = str.substr(spaceIndex + 1, i - spaceIndex);

st.push_back(num);

i = spaceIndex;

}

}

n = st.size();

for(int j = 0; j < n; j++)

{

string s = st[j];

if(s == "add" || s == "sub" || s == "mul" || s == "div")

{

if(res.size() < 2)

{

return;

}

int result = 0;

int num2 = res.top();

res.pop();

int num1 = res.top();

res.pop();

if(s == "add")

{

result = num1 + num2;

}

else if(s == "sub")

{

result = num2 - num1;

}

else if(s == "mul")

{

result = num1*num2;

}

else if(s == "div")

{

if(num1 == 0)

{

flag = false;

}

else

{

result = num2 / num1;

}

}

res.push(result);

}

else

{

res.push(atoi(s.c_str()));

}

}

if(!flag)

{

cout << "error" << endl;

}

else

{

cout << res.top() << endl;

}

}

int main()

{

string str;

cout << "please input the string:";

getline(cin, str);

Lisp(str);

return 0;

}

相关推荐
沐怡旸15 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥15 小时前
C++ 内存管理
c++
聚客AI15 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v18 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工20 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农21 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
moonlifesudo1 天前
322:零钱兑换(三种方法)
算法
感哥1 天前
C++ 多态
c++