#include <iostream>
#include <cctype>
#include <string>
#include <list>
#include <stack>
using namespace std;
char pop(list<char> & a) //Pops the stack and returns it, I use it to append to output vector
{
char result = a.front();
a.pop_front();
return result;
}
int main()
{
int num;
string in;
cin >> num;
string out; //stores outputed characters front operator stack
list<char> opr;
for(int zed=0; zed<num; zed++) {
cin >> in;
for(int i =0; i < in.length(); i++)
{
switch(in[i]) //Gets operator gets their precedence and pushes them into the stack(list) and
//output string
{
case '(': opr.push_front(in[i]);
break;
case ')': while(opr.front()!='(' && !opr.empty())
{
out.push_back(pop(opr));
}
opr.pop_front();
break;
case '-': if(opr.front() == '+' || '*' || '^' || '/' || '%')
{
out.push_back(pop(opr));
opr.push_front(in[i]);
}
else opr.push_front(in[i]);
out.push_back(' ');
break;
case '+': if(opr.front() == '-' || '*' || '^' || '/' || '%')
{
out.push_back(pop(opr));
opr.push_front(in[i]);
}
else opr.push_front(in[i]);
out.push_back(' ');
break;
case '*': if(opr.front() == '^' || '/' || '%')
{
out.push_back(pop(opr));
opr.push_front(in[i]);
}
else opr.push_front(in[i]);
out.push_back(' ');
break;
case '^': opr.push_front(in[i]);
out.push_back(' ');
break;
case '/': if(opr.front() == '^' || '*' || '%')
{
out.push_back(pop(opr));
opr.push_front(in[i]);
}
else opr.push_front(in[i]);
out.push_back(' ');
break;
default: if(isdigit(in[i]) || isalpha(in[i])) //Default: if character is a digit or a letter append it to output
out.push_back(in[i]);
}
}
while(!opr.empty()) //if the stack isn't empty push the rest into the output vector
{
out.push_back(pop(opr));
opr.pop_front();
}
out.erase(remove(out.begin(), out.end(),'('), out.end()); //remove those stupid parenthesis
out.push_back('
');
}
cout << out;
return 0;
}
Infix notation to Reverse Polish Notation
Leave a Reply
You must be logged in to post a comment.