-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluation_of_postfix.cpp
More file actions
92 lines (81 loc) · 1.93 KB
/
evaluation_of_postfix.cpp
File metadata and controls
92 lines (81 loc) · 1.93 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Writer : Mehadi Hasan Menon.
**/
#include <iostream>
#include <stack>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using std::stack;
using namespace std;
int evaluate_postfix(char *exp)
{
stack <int> s;
int len = strlen(exp);
for(int i = 0; i < len; )
{
int top1, top2;
if(exp[i] == '+')
{
top1 = s.top(); s.pop();
top2 = s.top(); s.pop();
s.push(top2 + top1);
i++;
// cout << "plus :" << top1 + top2 << endl;
}
else if(exp[i] == '-')
{
top1 = s.top(); s.pop();
top2 = s.top(); s.pop();
s.push(top2 - top1);
i++;
//cout << "sub : " << top2 - top1 << endl;
}
else if(exp[i] == '*')
{
top1 = s.top(); s.pop();
top2 = s.top(); s.pop();
s.push(top2 * top1);
i++;
// cout << "mul: " << top1 * top2 << endl;
}
else if(exp[i] == '/')
{
top1 = s.top(); s.pop();
top2 = s.top(); s.pop();
//cout << top1 << " " << top2 << endl;
s.push(top2 / top1);
i++;
//cout << "div : " << top2 / top1 << endl;
}
else
{
char tmp[10];
int k = 0;
while(exp[i] == ' ') {
i++;
}
while(isdigit(exp[i]))
{
tmp[k] = exp[i];
k++; i++;
}
tmp[k] = '\0';
if(strlen(tmp) > 0)
{
//std::cout << "tamp: " << tmp << std::endl;
s.push(atoi(tmp));
}
}
}
return s.top();
}
int main()
{
char exp[] = "5 6 2 + * 12 4 / -";
//while(gets(exp))
// {
std::cout << "After evaluation value is : " << evaluate_postfix(exp) << std::endl;
// }
return 0;
}