Last active
March 3, 2016 17:17
-
-
Save SohanChy/6d8924c8666c5de3b827 to your computer and use it in GitHub Desktop.
infix to postfix converter
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> | |
| #include <cmath> | |
| using namespace std; | |
| bool isOperator(char x) | |
| { | |
| if(x == '+' || x == '-' || x == '*' || x == '/' || x == '^') | |
| { | |
| return true; | |
| } | |
| else return false; | |
| } | |
| bool isOperand(char x) | |
| { | |
| if( (x >= '0' && x<='9') || (x >= 'a' && x<='z') || (x >='A' && x<='Z') ) | |
| { | |
| return true; | |
| } | |
| else return false; | |
| } | |
| bool isLowOperator(char x, char y) | |
| { | |
| int valX = 0, valY = 0; | |
| if(x=='*' || x=='/') | |
| { | |
| valX = valX + 1; | |
| } | |
| if(x=='^') | |
| { | |
| valX = valX + 2; | |
| } | |
| if(y=='*' || y=='/') | |
| { | |
| valY = valY + 1; | |
| } | |
| if(y=='^') | |
| { | |
| valY = valY + 2; | |
| } | |
| if(valX < valY) | |
| { | |
| //cout<<x<<"is lower than"<<y<<endl; | |
| return true; | |
| } | |
| else return false; | |
| } | |
| int main() | |
| { | |
| /* | |
| Infix to postfix | |
| */ | |
| { | |
| stack<char> myStack; | |
| string infix = "2*3/(2-1)+5*3"; | |
| infix = infix + ')'; | |
| myStack.push('('); | |
| string p = ""; | |
| int len = infix.length(); | |
| for(int i =0; i<len && myStack.empty() != true; i++) | |
| { | |
| if(isOperand(infix[i])) | |
| { | |
| p = p + infix[i]; | |
| } | |
| else if(infix[i] == '(') | |
| { | |
| myStack.push(infix[i]); | |
| } | |
| else if( isOperator(infix[i]) ) | |
| { | |
| while( isOperator(myStack.top()) && (isLowOperator(infix[i],myStack.top()) != true)) | |
| { | |
| p = p + myStack.top(); | |
| myStack.pop(); | |
| } | |
| myStack.push(infix[i]); | |
| } | |
| else if( infix[i] == ')' ) | |
| { | |
| while(myStack.top() != '(') | |
| { | |
| p = p + myStack.top(); | |
| myStack.pop(); | |
| } | |
| myStack.pop(); | |
| } | |
| cout<<"STEP "<<i<<" : "<<p; | |
| if(!myStack.empty()){ | |
| cout<<myStack.top();} | |
| cout<<endl; | |
| } | |
| cout<<endl<<"RESULT : "<<p<<endl; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment