Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool is_operator(char x);
- int main()
- {
- string expression;
- cout<<"\tEnter Infix Expression: \n\t-->";
- getline(cin,expression);
- string postfix = Infix_Postfix(expression);
- cout<<"\n\tCorresponding Postfix Expression: \n\t-->"<<postfix;
- return 0;
- }
- bool is_operator(char x)
- {
- if (x == '*' || x == '/' || x == '+' || x == '-')
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- string Infix_Postfix(string X)
- {
- STACK<char> s = STACK<char>();
- s.push('[');
- X.append("]");
- string Y;
- int index = 0;
- while(!s.is_empty())
- {
- for(int i = 0; i < X.length(); i++)
- {
- if(X[i] == '(')
- {
- s.push(X[i]);
- }
- else if (X[i] == ')')
- {
- while(!s.is_empty() && s.get_top() != '(')
- {
- Y = Y + s.get_top();
- s.pop();
- }
- s.pop();
- }
- else if (is_operator(X[i]))
- {
- if(X[i] == '+' || X[i] == '-')
- {
- while(s.get_top() == '*' || s.get_top() == '/' || s.get_top() == '+' || s.get_top() == '-')
- {
- Y = Y + s.get_top();
- s.pop();
- }
- s.push(X[i]);
- }
- else if (X[i] == '*' || X[i] == '/')
- {
- while(s.get_top() == '*' || s.get_top() == '/' )
- {
- Y = Y + s.get_top();
- s.pop();
- }
- s.push(X[i]);
- }
- }
- else if (X[i] == ']')
- {
- while(s.get_top() != '[')
- {
- Y = Y + s.get_top();
- s.pop();
- }
- s.pop();
- }
- else
- Y = Y + X[i];
- }
- return Y;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement