Realized the power of STL....
Solution:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
char a;
stack<char> s;
char arr[1001];
cin>>arr;
int len=strlen(arr);
for(int i=0;i<len;i++)
{
if(arr[i]=='(')
s.push(arr[i]);
else if(arr[i]==')')
{
while(s.top()!='(')
{
cout<<s.top();
s.pop();
}
s.pop();
}
else if(arr[i]=='+' || arr[i]=='-' ||arr[i]=='*' ||arr[i]=='/' ||arr[i]=='^' )
s.push(arr[i]);
else
cout<<arr[i];
}
cout<<endl;
}
return 0;
}
The problem would be made more difficult if expression wasn't in the RNP form
like ((a^b+c)/(d/e)) RNP form: (((a^b)+c)/(d/e))
Code for that keeping my preference order as (+,-)->(*,/) not considering ^:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char a;
stack<char> s;
char arr[1001];
cin>>arr;
int len=strlen(arr);
for(int i=0;i<len;i++)
{
if(arr[i]=='(')
s.push(arr[i]);
else if(arr[i]==')')
{
while(s.top()!='(')
{
cout<<s.top();
s.pop();
}
s.pop();
}
else if(arr[i]=='+' || arr[i]=='-')
{
while(s.top()!='(')
{
if(s.top()=='*' || s.top()=='/'||s.top()=='+' || s.top()=='-')
{
cout<<s.top();
s.pop();
}
else
break;
}
s.push(arr[i]);
}
else if(arr[i]=='*' || arr[i]=='/')
{
while(s.top()!='(')
{
if(s.top()=='/' || s.top()=='*')
{
cout<<s.top();
s.pop();
}
else
break;
}
s.push(arr[i]);
}
else
cout<<arr[i];
}
}
No comments:
Post a Comment