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;

}

相关推荐
qianbo_insist3 分钟前
simple c++ 无锁队列
开发语言·c++
zengy54 分钟前
Effective C++中文版学习记录(三)
数据结构·c++·学习·stl
MinBadGuy1 小时前
【GeekBand】C++设计模式笔记5_Observer_观察者模式
c++·设计模式
自由的dream1 小时前
0-1背包问题
算法
2401_857297911 小时前
招联金融2025校招内推
java·前端·算法·金融·求职招聘
良月澪二3 小时前
CSP-S 2021 T1廊桥分配
算法·图论
wangyue43 小时前
c# 线性回归和多项式拟合
算法
&梧桐树夏3 小时前
【算法系列-链表】删除链表的倒数第N个结点
数据结构·算法·链表
QuantumStack4 小时前
【C++ 真题】B2037 奇偶数判断
数据结构·c++·算法
今天好像不上班4 小时前
软件验证与确认实验二-单元测试
测试工具·算法