Skip to content

Instantly share code, notes, and snippets.

@rishi93
Last active August 16, 2016 11:25
Show Gist options
  • Select an option

  • Save rishi93/2c61fd9eea9943891207 to your computer and use it in GitHub Desktop.

Select an option

Save rishi93/2c61fd9eea9943891207 to your computer and use it in GitHub Desktop.
Transform the Expression - ONP
#include <iostream>
#include <stack>
using namespace std;
string reversePolishNotation(string expression){
stack<char> operatorStack;
string result = "";
for(int i=0; i<expression.length(); i++){
//If it is '(' then ignore
if(expression[i] == '('){
continue;
}
//Keep writing operands to the result string
else if(isalpha(expression[i])){
result += expression[i];
}
//When you encounter a ')' pop the operator from the operator stack
else if(expression[i] == ')'){
result += operatorStack.top();
operatorStack.pop();
}
//When you encounter a operator, push it to the operator stack
else{
operatorStack.push(expression[i]);
}
}
return result;
}
int main(){
//For Fast IO
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
string expression;
cin>>t;
for(int testcase=0; testcase<t; testcase++){
cin>>expression;
cout<<reversePolishNotation(expression)<<"\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment