Saturday, February 7, 2015

Infix to Postfix using stack in C++

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class stack
{ public:
  int top,t,i;char e[10],li[20];
  void push(char c);
  char pop();
  char pop2();
  char arr[10],h;
  int random();
};
void stack::push(char c)
{arr[++top]=c;
}
char stack::pop()
{ while(arr[top]=='-'  ||  arr[top]=='+'  ||  arr[top]=='*' || arr[top]=='/')
  e[++t]=arr[top--];
  push(li[i]);
}
char stack::pop2()
{ while(arr[top]=='*' || arr[top]=='/')
  e[++t]=arr[top--];
  push(li[i]);
}
int stack::random()
{ if(arr[0]=='+' && arr[1]=='-')
   {pop();}
   else if((arr[top]=='*') && (arr[(top+1)]=='-' || arr[top+1]=='+'))
   pop();
}
int main()
{stack s;int j,k,z;
 s.top=-1;s.t=-1;
 cout<<"Enter the infix expression:\n";
 cin.getline(s.li,20);
 j=strlen(s.li);
 cout<<"Hence the postfix of this expression is:\n";
 for(s.i=0;s.i<j;s.i++)
  {if(s.li[s.i]=='+')
     {if(s.top==-1)
 {s.push('+');}
 else
 {s.pop();
  for(k=0;k<=s.t;k++)
  {cout<<s.e[k];}}
  s.t=-1;}
   else if(s.li[s.i]=='-')
     {if(s.top==-1)
 {s.push('-');}
 else
 {s.pop();
  for(k=0;k<=s.t;k++)
  {cout<<s.e[k];}}
  s.t=-1;}
   else if(s.li[s.i]=='*')
    {if(s.top=='-' || s.top=='+' || s.top==-1)
 {s.push('*');}
 else
 {s.pop2();
  for(k=0;k<=s.t;k++)
  {cout<<s.e[k];}}
  s.t=-1;}
   else if(s.li[s.i]=='/')
    {if(s.top=='-' || s.top=='+'  ||  s.top==-1)
 {s.push('/');}
 else
 {s.pop2();
  for(k=0;k<=s.t;k++)
  {cout<<s.e[k];}}
  s.t=-1;}
   else
    cout<<s.li[s.i];
  }
  for(k=s.top;k>=0;k--)
  cout<<s.arr[k];
}

No comments:

Post a Comment

Contributors

Translate