描述 |
|
---|---|
知识点 | 栈 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | 输入算术表达式 |
输出 | 计算出结果值 |
样例输入 | 400+5 |
样例输出 | 405 true |
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <map>
#include <algorithm>
using namespace std;
map<char, int> priority;//保存运算符优先级
vector<string> vec;//保存后缀表达式
//函数getExpression用于获取字符串的后缀表达式
//输入:str中缀表达式字符串
//输出:vec后缀表达式
//算法参考网址:http://blog.csdn.net/u012507347/article/details/52245233
void getExpression(string str)
{
stack<char> s; //保存运算符
for (int i = 0; i < str.length(); i++)
{
if (isalnum(str[i]))
{
string num;
while (isalnum(str[i]))
{
num.push_back(str[i]);
i++;
}
vec.push_back(num);
i--;
}
else if (str[i] == '(')
{
s.push(str[i]);
}
else if (str[i] == ')')
{
while (s.top() != '(')
{
string tmp;
tmp.push_back(s.top());
vec.push_back(tmp);
s.pop();
}
s.pop();
}
else
{
if(!s.empty() && priority[s.top()] <= priority[str[i]]
&& s.top() != '(')
{
string tmp;
tmp.push_back(s.top());
vec.push_back(tmp);
s.pop();
s.push(str[i]);
}
else
s.push(str[i]);
}
}
while (!s.empty())
{
string tmp;
tmp.push_back(s.top());
vec.push_back(tmp);
s.pop();
}
}
//计算后缀表达式的结果
int computerExp()
{
stack<int> s;
for (int i = 0; i < vec.size(); i++)
{
if (isalnum(vec[i][0]))
{
int num = atoi(vec[i].c_str());
s.push(num);
}
else
{
int value1 = s.top();
s.pop();
int value2 = s.top();
s.pop();
int value3;
switch (vec[i][0])
{
case '+':
value3 = value2 + value1;
break;
case '-':
value3 = value2 - value1;
break;
case '*':
value3 = value2 * value1;
break;
case '/':
value3 = value2 / value1;
break;
}
s.push(value3);
}
}
return s.top();
}
void main()
{
priority['+'] = 1;
priority['-'] = 1;
priority['*'] = 0;
priority['/'] = 0;
string str;
cin >> str;
getExpression(str);
cout << computerExp()<<endl;
cout << "true";
}