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;

}

相关推荐
AA陈超17 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-01.创建游戏玩法标签
c++·游戏·ue5·游戏引擎·虚幻
IT小番茄1 小时前
Kubernetes云平台管理实战:自动加载到负载均衡(七)
算法
笑口常开xpr1 小时前
【C++继承】深入浅出C++继承机制
开发语言·数据结构·c++·算法
代码AC不AC1 小时前
【C++】红黑树实现
c++·红黑树·底层结构
让我们一起加油好吗2 小时前
【基础算法】DFS
算法·深度优先
liu****2 小时前
2.c++面向对象(三)
开发语言·c++
linux kernel2 小时前
第二十四讲:C++中的IO流
开发语言·c++
爱学习的小鱼gogo3 小时前
python 矩阵中寻找就接近的目标值 (矩阵-中等)含源码(八)
开发语言·经验分享·python·算法·职场和发展·矩阵
红纸2813 小时前
Subword算法之WordPiece、Unigram与SentencePiece
人工智能·python·深度学习·神经网络·算法·机器学习·自然语言处理
CUMT_DJ4 小时前
从零复现论文(1)——通感一体化实现协作基站分配与资源分配(CBARA)策略
算法·通感一体化