2020年10月7日 星期三

invert infix to postfix or prefix

 infix to postfix

infix to prefix



#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;

bool isOperator(char c)
{
	if (c == '+' || c == '/' || c == '-' || c == '*') return true;
	return false;
}
int priority(char c)
{
	if (c == '+' || c == '-') return 1;
	if (c == '*' || c == '/') return 2;
}
string to_postfix(string s)
{
	string postfix = "";
	stack<char> st;
	s += ")";
	st.push('(');
	for (int i = 0; i < s.size(); i++)
	{
		if (s[i] == '(') st.push(s[i]);
		else if (isOperator(s[i]))
		{
			while (st.top()!='('&&priority(st.top()) >= priority(s[i]))
			{
				postfix += st.top();
				st.pop();
			}
			st.push(s[i]);
		}
		else if (s[i] == ')')
		{
			while (st.top() != '(')
			{
				postfix += st.top();
				st.pop();
			}
			st.pop();
		}
		else
		{
			postfix += s[i];
		}
	}
	while (!st.empty())
	{
		postfix += st.top();
		st.pop();
	}
	return postfix;
}
string to_prefix(string s)
{
	reverse(s.begin(), s.end());
	for (int i = 0; i < s.size(); i++)
	{
		if (s[i] == '(') s[i] = ')';
		else if (s[i] == ')') s[i] = '(';
	}
	s = to_postfix(s);
	reverse(s.begin(), s.end());
	return s;
}
int main()
{
	string s;
	getline(cin, s);
	string postfix = to_postfix(s);
	cout << postfix << endl;
	cout << to_prefix(s);
	return 0;
}