#include<iostream>
#include<map>
#include<stack>
#include<queue>
using namespace std;
void text01()
{
//设置优先级!
map<char, int>map;
map.insert(make_pair('#', 0));
map.insert(make_pair('+', 1));
map.insert(make_pair('-', 1));
map.insert(make_pair('*', 2));
map.insert(make_pair('/', 2));
map.insert(make_pair('(', 3));
map.insert(make_pair(')', 3));
//利用map容器来表示优先级
stack<char>stack;
queue<char>queue;
cout << "请输入中缀表达式:" << endl;
string str;
cin >> str;
stack.push('#');
int length = str.size();
if (str.at(0) == '+' || str.at(0) == '-' || str.at(0) == '*' || str.at(0) == '/')return ;
if (str.at(length - 1) == '+' || str.at(length - 1) == '-' || str.at(length - 1) == '*' || str.at(length - 1) == '/')return ;
//char temp;
for (int i = 0; i < str.size(); i++)
{
if (str.at(i) == '+' || str.at(i) == '-' || str.at(i) == '*' || str.at(i) == '/' || str.at(i) == '(' || str.at(i) == ')')
{
while (1)
{
if (map[str.at(i)] > map[stack.top()])//如果优先级高的话就进栈
{
stack.push(str.at(i));
if (stack.top() == ')')//如果栈顶为‘)’的话就把()之间的全部出栈,进入到queue里去;
{
while (1)
{
stack.pop();
if (stack.top() == '(')
{
stack.pop();
break;
}
queue.push(stack.top());
}
}
break;
}
if (map[str.at(i)] <= map[stack.top()])//如果优先级低于栈顶或与栈顶优先级相同的话,先判断是不是‘(’,如果不是就出栈
{
if (stack.top() == '(')//如果栈顶为‘(’时,那么直接进栈即可
{
stack.push(str.at(i));
break;
}
else
{
queue.push(stack.top());
stack.pop();
}
}
}
}
else//如果不是+-*/,那么进入队列里
{
queue.push(str.at(i));
}
if (i == str.size() - 1)
{
while (stack.top() != '#')
{
queue.push(stack.top());
stack.pop();
}//当它遍历完的时候,stack里面的全部出栈
}
}
cout << "后缀表达式为:" << endl;
while (!queue.empty()) {
cout << " " << queue.front();
queue.pop();
}
cout << endl;
}
int main()
{
text01();
system("pause");
return 0;
}
中缀转后缀表达式
最新推荐文章于 2024-07-25 12:39:48 发布