Last active
August 16, 2016 11:25
-
-
Save rishi93/2c61fd9eea9943891207 to your computer and use it in GitHub Desktop.
Transform the Expression - ONP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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