I have a postfix expression and I need to evaluate it also check for its validity. There can be a way in which I first evaluate the expression and if it is valid then I go for its calculation But that involves doing the same work twice. How to do it in a single call?
My code is below where the function works for evaluation and I want to return for error where it is written
//return error
Any help how to proceed with this?
#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
int isOperand(char s){
if(s >= '0' && s<= '9')
return 1;
return 0;
}
int applyOperation(int val1, int val2, char expression){
switch(expression){
case '+':
return val2+val1;
case '-':
return val2-val1;
case '*':
return val2*val1;
case '/':
return val2/val1;
}
}
int evaluatePostfix(char* exp){
stack<int> operandStack;
int l = strlen(exp);
for(int i=0;i<l;i++){
if(isOperand(exp[i]))
operandStack.push(exp[i]-'0');
else{
if(operandStack.empty())
//return error
int val1 = operandStack.top();
operandStack.pop();
if(operandStack.empty())
//return error
int val2 = operandStack.top();
operandStack.pop();
int result = applyOperation(val1,val2,exp[i]);
operandStack.push(result);
}
}
int topElem = operandStack.top();
operandStack.pop();
if(!operandStack.empty())
//return error
return operandStack.top();
}
int main()
{
char exp[] = "231*+9-";
printf ("Value of %s is %d", exp, evaluatePostfix(exp));
return 0;
}
Aucun commentaire:
Enregistrer un commentaire