Postfix Evaluation Using Array Stack In Data Structure Using C++

Data Structure Using C++

Stack Data Structure

Postfix Evaluation Using Array Stack

class stack
{
 private:
  int *ptr;
  int size;
  int current;
 public:
  stack(int l);
  void push (int val);
  int pop ();
  int top ();
  int isFull ();
  int isEmpty();
};
stack::stack(int l)
{
 ptr=new int [l];
 current=-1;
 size=l;
}
void stack::push(int val)
{
 if(!isFull()){
  ptr[++current]=val;  
 }else{
  cout<<"Stack is Full!"<<endl;
 }
}
int stack::pop ()
{
 if(!isEmpty()){
  return ptr[current--];
 }else{
  cout<<"Stack is Empty!"<<endl;
 }
}
int stack::top ()
{
 return ptr[current];
}
int stack::isFull()
{
 return current==--size;
}
int stack::isEmpty()
{
 return current==-1;
}
int main ()
{
 stack s(10);
 char str[10]={'1','2','3','*','4','/','+'};
 int i=0;
 int op1, op2, result=0, ans=0;
 while(str[i]!='\0')
 {
  char ch=str[i];
  if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^')
  {
   op2=s.pop();
   op1=s.pop();
   cout<<op1<<" "<<op2<<endl;
   if(ch=='+')
   {
    result=op1+op2;
   }
   else if(ch=='-')
   {
    result=op1-op2;
   }
   else if(ch=='*')
   {
    result=op1*op2;
   }
   else if(ch=='/')
   {
    if(op2!=0)
    {
     result=op1/op2;
    }
   }
   else if(ch=='^'){
    result=pow(op1,op2);
   }
   cout<<endl<<result<<endl;
   s.push(result);
  }
  else
  {
   ch=ch-48;
   s.push(ch);
  }
  i++;
 }
 ans=s.pop();
 cout<<"Result is : "<<ans<<endl;
}

Let me know in the comment section if you have any question.

Previous Post:
Stack Using Linked List In Data Structure Using C++

Comments