首先確定基本運算符的優先級
pair<string, int>(")", 3),
pair<string, int>("*", 2),
pair<string, int>("/", 2),
pair<string, int>("+", 1),
pair<string, int>("-", 1),
pair<string, int>("(", 0),
中綴轉換後綴算法流程:
遍歷中綴表達式
1.判斷是否爲運算數值,如果是,放入結果向量
2.判斷是否爲左括號,如果是,入棧
3.判斷是否爲右括號,如果是,不入棧,並且依次彈出棧頂元素至結果向量,直到遇見右括號,右括號只彈出不加入結果向量。
4.判斷是否爲運算符
如果棧爲空或者當前遍歷到的運算符的優先級大於棧頂元素的優先級,直接入棧
如果否則在棧不爲空且當前遍歷到的運算符的優先級小於等於棧頂元素的優先級的情況下,並且依次彈出棧頂元素至結果向量,並且把當前遍歷的運算符入棧
5.判斷遍歷完後棧是否爲空,如果不爲空,則依次取棧頂元素至結果向量。
Show code.
#include<iostream>
#include<stack>
#include<vector>
#include<string>
#include<map>
#include<utility>
using namespace std;
map<string, int>level =
{
pair<string, int>(")", 3),
pair<string, int>("*", 2),
pair<string, int>("/", 2),
pair<string, int>("+", 1),
pair<string, int>("-", 1),
pair<string, int>("(", 0),
};
int cal(int a ,int b,char c)
{
switch (c)
{
case '-': return a - b; break;
case '+': return a + b; break;
case '*': return a * b; break;
case '/': return a / b; break;
default:break;
}
}
int calSuffix(vector<string>str)
{
stack<string>s;
string::size_type npos;
for (int i = 0; i < str.size(); i++)
{
if (str[i][0] >= '0' && str[i][0] <= '9')
s.push(str[i]);
else
{
int a = atoi(s.top().c_str()); s.pop();
int b = atoi(s.top().c_str()); s.pop();
int cal_res = cal(b, a, str[i][0]);
s.push(std::to_string(cal_res));
}
}
return atoi(s.top().c_str());
}
vector<string> transferMiddleToSuffix(vector<string>str)
{
stack<string>s;
vector<string>res;
for (int i = 0; i < str.size(); i++)
{
if (str[i] >= "0" && str[i] <= "9")
res.push_back(str[i]);
else if(str[i] == "(")
s.push(str[i]);
else if (str[i] == ")")
{
while (s.top() != "(")
{
res.push_back(s.top());
s.pop();
}
s.pop();
}
else
{
//If level of curr higher than top of stack
//Out and push into vec_res
if ( s.empty() || (level.find(str[i])->second > level.find(s.top())->second))
s.push(str[i]);
//Else out until it encounters lower one or "("
else
{
while ( !s.empty() && ( level.find(str[i])->second <= level.find(s.top())->second))
{
res.push_back(s.top());
s.pop();
}
s.push(str[i]);
}
}
}
while (!s.empty())
{
res.push_back(s.top());
s.pop();
}
return res;
}
void main()
{
vector<string> suffix = { "6", "5", "2", "3", "+", "8", "*", "+", "3", "+", "*" };
cout << calSuffix(suffix) << endl;
vector<string> middle = { "1" ,"+", "(", "2", "-", "3", ")", "*", "4", "+", "4", "/", "2" };
vector<string> middle_test = { "3", "+", "(", "2", "-", "5", ")", "*", "6", "/", "3"};
vector<string> test = transferMiddleToSuffix(middle);
for (int i = 0; i < test.size(); i++)
cout << test[i] << " ";
cout << "Cal suffix : " << calSuffix(test);
}