Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<string>
- #include "StackType.h"
- using namespace std;
- int Precedence(char op);
- string Postfix(string infix);
- int main()
- {
- string infix;
- getline(cin, infix);
- cout << Postfix(infix) << endl;
- return 0;
- }
- string Postfix(string infix)
- {
- StackType<char> stack;
- string postfix;
- int i=0;
- char token,popped;
- bool done;
- token = infix[0];
- while(token!='=')
- {
- if(token>='0' && token <='9')
- postfix+=token;
- if(token==')')
- {
- popped=stack.Top();
- stack.Pop();
- while(popped!='(')
- {
- postfix+=popped;
- popped=stack.Top();
- stack.Pop();
- }
- }
- if(token=='+' || token=='-' || token=='*' || token=='/' || token=='(' || token=='=')
- {
- if(token!='(')
- {
- done=false;
- while(!stack.IsEmpty() && !done)
- if(Precedence(stack.Top())>=Precedence(token))
- {
- postfix+=stack.Top();
- stack.Pop();
- }else
- done=true;
- }
- stack.Push(token);
- }
- i++;
- token=infix[i];
- }
- while(!stack.IsEmpty())
- {
- postfix+=stack.Top();
- stack.Pop();
- }
- return postfix;
- }
- int Precedence(char op)
- {
- switch(op)
- {
- case '/': return 3;
- case '*': return 3;
- case '+': return 2;
- case '-': return 2;
- case '(': return 0;
- default: return 1;
- }
- }
Add Comment
Please, Sign In to add comment