字符串 栈

思路:中缀转后缀;负数添0;

四则运算,最常用的当然是逆波兰方法,现将表达式由中缀表达式转化为后缀表达式,然后再使用栈计算即可。这两步下来,估计没有三四百行代码是实现不了的。

中缀表达式转前缀后缀表达式

将中缀表达式转换为后缀表达式的算法思想:
数字时,加入后缀表达式;
运算符:
a. 若为 '(',入栈;
b. 若为 ')',则依次把栈中的的运算符加入后缀表达式中,直到出现'(',从栈中删除'(' ;
c. 若为 除括号外的其他运算符, 当其优先级高于除'('以外的栈顶运算符时,直接入栈。否则从栈顶开始,依次弹出比当前处理的运算符优先级高和优先级相等的运算符,直到一个比它优先级低的或者遇到了一个左括号为止。

高优先级可以压迫低优先级!

人工实现转换

这里我给出一个中缀表达式:a+b*c-(d+e)
第一步:按照运算符的优先级对所有的运算单位加括号:式子变成了:((a+(b*c))-(d+e))
第二步:转换前缀与后缀表达式
前缀:把运算符号移动到对应的括号前面 ,则变成了:-( +(a *(bc)) +(de)) ,把括号去掉:-+a*bc+de 前缀式子出现。
后缀:把运算符号移动到对应的括号后面 ,则变成了:((a(bc)* )+ (de)+ )- ,把括号去掉:abc*+de+- 后缀式子出现。

比如:计算(2 + 1) * (13 + 5)

转换后得:((2+1)*(13+5))  ->  ((2 1) + (13 5) +) *  ->  2 1 + 13 5 + *
这里把后缀表达式存储到vector<string>中,实现栈的计算

#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
int main() {
string s;
while (cin >> s) {
stack<char> opera;
vector<int> numcnt;
string s1;//后缀表达式
//中缀表达式转后缀表达式
for (int i = 0;i<s.size();i++) {
if (s[i] >= '0'&&s[i] <= '9') {
int tmp = 0;
while (s[i] >= '0'&&s[i] <= '9') {
tmp++;
s1 += s[i];
i++;
}
i--;
numcnt.push_back(tmp);
}
else if (s[i] == '-' || s[i] == '+') {
if (s[i] == '-' && (s[i - 1] == '(' || s[i - 1] == '[' || s[i - 1] == '{'))
s1 += '0';
while (!opera.empty()&&(opera.top() == '*' || opera.top() == '/' || opera.top() == '+' || opera.top() == '-')) {
s1 += opera.top();
opera.pop();
}
opera.push(s[i]);
}
else if (s[i] == '*' || s[i] == '/') {
while (!opera.empty()&&(opera.top() == '*' || opera.top() == '/')) {
s1 += opera.top();
opera.pop();
}
opera.push(s[i]);
}
else if (s[i] == '(' || s[i] == '[' || s[i] == '{')
opera.push(s[i]);
else if (s[i] == ')') {
while (opera.top() != '(') {
s1 += opera.top();
opera.pop();
}
opera.pop();
}
else if (s[i] == ']') {
while (opera.top() != '[') {
s1 += opera.top();
opera.pop();
}
opera.pop();
}
else if (s[i] == '}') {
while (opera.top() != '{') {
s1 += opera.top();
opera.pop();
}
opera.pop();
}
else
cout << "Invalid input!" << endl;
}
while (!opera.empty()) {
s1 += opera.top();
opera.pop();
}
//计算后缀表达式的值
stack<int> nums;
int ind = 0;
for (int i = 0;i<s1.size();i++) {
if (s1[i] >= '0'&&s1[i] <= '9') {
int total = 0;
while (numcnt[ind]--)
total = 10 * total + (s1[i++] - '0');
i--;
nums.push(total);
ind++;
}
else {
int tmp1 = nums.top();
nums.pop();
int tmp2 = nums.top();
nums.pop();
if (s1[i] == '+')
nums.push(tmp2 + tmp1);
else if (s1[i] == '-')
nums.push(tmp2 - tmp1);
else if (s1[i] == '*')
nums.push(tmp2*tmp1);
else
nums.push(tmp2 / tmp1);
}
}
cout << nums.top() << endl;
}
}

原文地址:https://www.cnblogs.com/sweet-li/p/13140228.html