Evaluating A Postfix Expression Using Stack DataStructures

#include"stdafx.h"
#include<math.h>
#include<iostream>
# define MAX_STACK 150 
using namespace std;
class stacks
{
   int value,item,top;
   int stack[MAX_STACK];
   public:
      stacks()
      {
  top=(-1);
      }
      void push(float);
      float pop();
};

void stacks::push(float value)
{
   if(top==MAX_STACK)
   {
      cout<<"Stack is full!\nOverflow!";
  
      exit(0);
   }
   else
   top++;
   stack[top]=value;
}

float stacks::pop()
{
   if(top<0)
   {
      cout<<"Stack is empty!\nUnderflow!";
      exit(0);
   }
   else
   item=stack[top];
   top--;
   return(item);
}

int main()
{
   
   stacks stk1;
   char expression[150],oper_string[8],ch;
   oper_string[0]='\0';
   float value,operand1,operand2,val;
   int pos=0,p=0;
   cout<<"Enter a postfix expression: ";
   gets(expression);
   while(expression[pos]!='\0')
   {
      ch=expression[pos];
     
      if((isspace(ch)) &&(oper_string[0]!='\0'))
      {
  oper_string[p]='\0';
  stk1.push((atof(oper_string)));
  oper_string[0]='\0';
  p=0;
      }
      else if(ch==' ')
      {
  pos++;
  continue;
      }
      else if((isdigit(ch)))
      {
  oper_string[p]=ch;
  p++;
      }
         else
      {
  operand1=stk1.pop();
  operand2=stk1.pop();
  switch(ch)
  {
     case '+':
        val=operand2+operand1;
        break;
     case '-':
        val=operand2-operand1;
        break;
     case '*':
        val=operand2*operand1;
        break;
     case '/':
        val=operand2/operand1;
        break;
     case '^':
        val=pow(operand2,operand1);
        break;
     default: break;
  }
  stk1.push(val);
      }
      pos++;
   }
   cout<<"\n answere is= "<<val<<endl;
}

Comments

Popular posts from this blog

Check if ViewBag is null or doesn't exist

Using Progress Bar In C#

Jquery serer side datatables in asp.net