-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcall_to_postfix.cpp
56 lines (51 loc) · 1.08 KB
/
call_to_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
#include<stack>
#include<cstring>
#include<iostream>
using namespace std;
bool isNumeric(char ch)
{
if(ch>='0' && ch <='9')
return true;
return false;
}
bool isOperator(char ch)
{
if(ch=='*' || ch=='/' || ch=='-' ||ch=='+')
return true;
return false;
}
int performOperation(char ch , int op1 , int op2)
{
if(ch=='*') return op1*op2;
else if(ch=='-') return op1-op2;
else if(ch=='+') return op1+op2;
return op1/op2;
}
int evaluatePostfix(string exp)
{
stack<int> S;
int n = exp.length();
for(int i=0;i<n;i++)
{
if(isNumeric(exp[i]))
{
int num = 0;
while(isNumeric(exp[i]))
{
num = num*10 + int(exp[i])-48;
i++;
}
S.push(num);
}
if(exp[i]==',') continue;
int res;
if(isOperator(exp[i]))
{
int op2 = S.top(); S.pop();
int op1 = S.top(); S.pop();
res = performOperation(exp[i],op1,op2);
S.push(res);
}
}
return S.top();
}