-
Notifications
You must be signed in to change notification settings - Fork 2
/
infixEvaluation.cpp
127 lines (109 loc) · 3.01 KB
/
infixEvaluation.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include<bits/stdc++.h>
using namespace std;
int getPriority(char ch) {
if(ch == '+' || ch == '-') return 1;
else if(ch == '*' || ch == '/') return 2;
else if(ch == '^') return 3;
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || (ch == '.')) return 0;
else return -1;
}
string infixToPostFix(string infix) {
stack<char>stk;
int i = 0;
string postfix = "";
for(i = 0; infix[i]; i++) {
char ch = infix[i];
if(ch == '(') stk.push(ch);
else if(ch == ')') {
while(!stk.empty() && stk.top() != '(') {
postfix += stk.top();
postfix += ',';
stk.pop();
}
stk.pop();
}
else {
int priority = getPriority(ch);
if(priority == 0) {
while(getPriority(infix[i]) == 0) {
postfix += infix[i];
i++;
}
i--;
postfix += ',';
}
else {
if(stk.empty()) stk.push(ch);
else {
while(!stk.empty() && stk.top() != '(' && (priority <= getPriority(stk.top()))) {
postfix += stk.top();
postfix += ',';
stk.pop();
}
stk.push(ch);
}
}
}
}
while(!stk.empty()) {
postfix += stk.top();
postfix += ',';
stk.pop();
}
postfix.erase(postfix.end()-1);
return postfix;
}
double calculate(double a, double b, char ch) {
switch(ch) {
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
case '^':
return pow(a, b);
}
}
double postfixEvaluate(string postfix) {
stack<double>stk;
int i;
for(i = 0; i < postfix[i]; i++) {
char ch = postfix[i];
if(ch == ',' || ch == ' ') continue;
else if(ch >= '0' && ch <= '9') {
string str = "";
while(postfix[i] != ',' && postfix[i]) {
str += postfix[i];
i++;
}
double num = stod(str);
stk.push(num);
}
else if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch < 'Z') {
double value;
cout << "Enter the value of " << ch << " : ";
cin >> value;
stk.push(value);
}
else {
double b = stk.top();
stk.pop();
double a = stk.top();
stk.pop();
stk.push(calculate(a, b, ch));
}
}
return stk.top();
}
int main() {
string infix = "a+5.0*(2+3)-b";
string postfix = infixToPostFix(infix);
cout << "Infix : " << infix << endl;
cout << "Postfix : " << postfix << endl;
double ans = postfixEvaluate(postfix);
cout << "Answer : " << ans << endl;
return 0;
}