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 分钟前
《机器学习导论》第 5 章-多元方法
人工智能·python·算法·机器学习·numpy·matplotlib·多元方法
liu****30 分钟前
2.深入浅出理解虚拟化与容器化(含Docker实操全解析)
运维·c++·docker·容器·虚拟化技术
A9better38 分钟前
C++——不一样的I/O工具与名称空间
开发语言·c++·学习
R1nG8631 小时前
CANN资源泄漏检测工具源码深度解读 实战设备内存泄漏排查
数据库·算法·cann
王老师青少年编程1 小时前
2024年信奥赛C++提高组csp-s初赛真题及答案解析(阅读程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
_OP_CHEN1 小时前
【算法基础篇】(五十六)容斥原理指南:从集合计数到算法实战,解决组合数学的 “重叠难题”!
算法·蓝桥杯·c/c++·组合数学·容斥原理·算法竞赛·acm/icpc
MSTcheng.1 小时前
【C++】C++11新特性(三)
开发语言·c++·c++11
田野追逐星光1 小时前
STL容器list的模拟实现
开发语言·c++·list
TracyCoder1231 小时前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode
StandbyTime2 小时前
《算法笔记》学习记录-第二章 C/C++快速入门
c++·算法笔记