forked from Vishal-Aggarwal0305/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate postfix.cpp
74 lines (63 loc) · 1.74 KB
/
evaluate postfix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int EvaluatePostfix(string expression);
int PerformOperation(char operation, int operand1, int operand2);
bool IsOperator(char C);
bool IsNumericDigit(char C);
int main()
{
string expression;
cout<<"Enter Postfix Expression \n";
getline(cin,expression);
int result = EvaluatePostfix(expression);
cout<<"Output = "<<result<<"\n";
}
int EvaluatePostfix(string expression)
{
stack<int> S;
for(int i = 0;i< expression.length();i++)
{
if(expression[i] == ' ' || expression[i] == ',') continue;
else if(IsOperator(expression[i]))
{
int operand2 = S.top(); S.pop();
int operand1 = S.top(); S.pop();
int result = PerformOperation(expression[i], operand1, operand2);
S.push(result);
}
else if(IsNumericDigit(expression[i]))
{
int operand = 0;
while(i<expression.length() && IsNumericDigit(expression[i]))
{
operand = (operand*10) + (expression[i] - '0');
i++;
}
i--;
S.push(operand);
}
}
return S.top();
}
bool IsNumericDigit(char C)
{
if(C >= '0' && C <= '9') return true;
return false;
}
bool IsOperator(char C)
{
if(C == '+' || C == '-' || C == '*' || C == '/')
return true;
return false;
}
int PerformOperation(char operation, int operand1, int operand2)
{
if(operation == '+') return operand1 +operand2;
else if(operation == '-') return operand1 - operand2;
else if(operation == '*') return operand1 * operand2;
else if(operation == '/') return operand1 / operand2;
else cout<<" Error \n";
return -1;
}