-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_calculationOf_postfix_Expresions.cpp
83 lines (69 loc) · 1.48 KB
/
stack_calculationOf_postfix_Expresions.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
75
76
77
78
79
80
81
82
83
//this prgram calculates mathmatical problems
// expressed by postfix notaton
// the notation is for example ab+c* means (a+b)*c
// there are no bracket invloved in postfix expresion
// that the reason they are usefull specialy in complier technologies
#include <stack>
#include <cstring>
class postfix
{
private:
stack<int> estack;
char* exp;
public:
postfix()
{
exp = "#4#2+-";
}
postfix(char* ie)
{
exp= ie;
}
int evaluate(char ope);
int calculate();
int do_the_math(int a,int b,char ope);
};
int postfix::calculate()
{
for(int i = 0;exp[i] !='\0';i++)
{
if(exp[i] == '#')
{
i++;
int j = atoi( &exp[i] );
estack.push(j);
}
else if(exp[i] == '=')
return estack.top();
else evaluate(exp[i]);
}
return -1;
}
int postfix::evaluate(char ope)
{
int a,b,rst;
if(!estack.empty()){
a = estack.top();
estack.pop();
}else return -1;
if(!estack.empty()){
b = estack.top();
estack.pop();
}else return -1;
rst = do_the_math(a,b,ope);
estack.push(rst);
return 1;
}
int postfix::do_the_math(int a,int b,char ope)
{
int rst;
if(ope == '+')
rst = b + a;
else if(ope == '-')
rst = b - a;
else if(ope == '*')
rst = b*a;
else if(ope == '/')
rst = b/a;
return rst;
}