#include<bits/stdc++.h>
using namespace std;
int priority(string ch)
{
if(ch == "^")
return 3;
else if(ch == "*" || ch == "/")
return 2;
else if(ch == "+" || ch == "-")
return 1;
else
return 0;
}
stack<string> converter(string ifix)
{
stack<string>pfix;
stack<string>s;
string ch = "";
int i, l = ifix.size();
for(i=0; i<l; i++)
{
while(ifix[i] != 32)
{
cout << ifix[i] << endl;
ch += ifix[i];
i++;
}
if(ifix[i] == 32)
i++;
if(ch == "(")
s.push(ch);
else if(ch == ")")
{
while(!s.empty() && s.top() != "(")
{
pfix.push(ch);
s.pop();
}
if(!s.empty() && s.top() == "(")
s.pop();
}
else
{
int p = priority(ch);
if(p == 0)
pfix.push(ch);
else if(s.empty())
s.push(ch);
else
{
while(!s.empty() && s.top() != "(" && p <= priority(s.top()))
{
pfix.push(ch);
s.pop();
}
s.push(ch);
}
}
ch.clear();
}
while(!s.empty())
{
pfix.push(s.top());
s.pop();
}
return pfix;
}
int main()
{
string s;
int n;
cin >> n;
while(n--)
{
cin >> s;
stack<string> ch;
ch = converter(s);
while(!ch.empty())
{
cout << ch.top() << endl;
ch.pop();
}
}
return 0;
}
using namespace std;
int priority(string ch)
{
if(ch == "^")
return 3;
else if(ch == "*" || ch == "/")
return 2;
else if(ch == "+" || ch == "-")
return 1;
else
return 0;
}
stack<string> converter(string ifix)
{
stack<string>pfix;
stack<string>s;
string ch = "";
int i, l = ifix.size();
for(i=0; i<l; i++)
{
while(ifix[i] != 32)
{
cout << ifix[i] << endl;
ch += ifix[i];
i++;
}
if(ifix[i] == 32)
i++;
if(ch == "(")
s.push(ch);
else if(ch == ")")
{
while(!s.empty() && s.top() != "(")
{
pfix.push(ch);
s.pop();
}
if(!s.empty() && s.top() == "(")
s.pop();
}
else
{
int p = priority(ch);
if(p == 0)
pfix.push(ch);
else if(s.empty())
s.push(ch);
else
{
while(!s.empty() && s.top() != "(" && p <= priority(s.top()))
{
pfix.push(ch);
s.pop();
}
s.push(ch);
}
}
ch.clear();
}
while(!s.empty())
{
pfix.push(s.top());
s.pop();
}
return pfix;
}
int main()
{
string s;
int n;
cin >> n;
while(n--)
{
cin >> s;
stack<string> ch;
ch = converter(s);
while(!ch.empty())
{
cout << ch.top() << endl;
ch.pop();
}
}
return 0;
}
Comments
Post a Comment