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;

}

相关推荐
浅川.251 小时前
xtuoj 不定方程的正整数解
算法
dog2501 小时前
让算法去学习,而不是去启发
学习·算法
草莓熊Lotso1 小时前
《算法闯关指南:动态规划算法--斐波拉契数列模型》--04.解码方法
c++·人工智能·算法·动态规划
alphaTao1 小时前
LeetCode 每日一题 2025/12/1-2025/12/7
数据库·算法·leetcode
1nv1s1ble1 小时前
[c++] cpp快速添加sqlite_orm
c++·sqlite
苏小瀚1 小时前
[算法]---分治-快排和归并
java·算法·leetcode
Jac_kie_層樓1 小时前
力扣hot100刷题记录(12.1)
算法·leetcode·职场和发展
陶陶name1 小时前
Metal Compute Pipeline:Metal-C++ 环境配置与简单算子实现
开发语言·c++
无限进步_1 小时前
寻找数组中缺失数字:多种算法详解与比较
c语言·开发语言·数据结构·算法·排序算法·visual studio
凌康ACG1 小时前
Sciter之子线程更新UI(八)
c++·sciter