Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<stack>
- using namespace std;
- class postfix{
- stack <char>a;
- public:
- int precedence(char c){
- if(c=='^'){
- return 3;
- }
- else if(c=='/' || c=='*')
- {
- return 2;
- }
- else if(c=='+' || c=='-'){
- return 1;
- }
- else{
- return -99;
- }
- }
- bool isoperator(char c){
- if(c=='*' || c=='/' || c=='^' || c== '+' || c=='-'){
- return true;
- }
- return false;
- }
- void infixtopostfix(string s){
- int i=0;
- while(s[i]!='\0'){
- if(s[i]=='('){
- a.push('(');
- }
- else if(s[i]>='0' && s[i]<='9'){
- cout<<s[i];
- }
- else if(isoperator(s[i])){
- if(a.empty()){
- a.push(s[i]);
- }
- else if(a.top()=='('){
- a.push(s[i]);
- }
- else if(precedence(s[i])>precedence(a.top())){
- a.push(s[i]);
- }
- else if(precedence(s[i])<=precedence(a.top())){
- while(!a.empty() && precedence(s[i])<=precedence(a.top())){
- cout<<a.top();
- a.pop();
- }
- a.push(s[i]);
- }
- }
- else if(s[i] ==')'){
- while(a.top()!='(' && !a.empty()){
- cout<<a.top();
- a.pop();
- }
- a.pop();
- }
- i++;
- }
- while(!a.empty()){
- cout<<a.top();
- a.pop();
- }
- }
- };
- int main(){
- postfix p;
- p.infixtopostfix("(1+2)*3^2");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement