-
Notifications
You must be signed in to change notification settings - Fork 0
/
AlgebraicExpression.cpp
89 lines (78 loc) · 2.14 KB
/
AlgebraicExpression.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
#include <stdio.h>
#include "AlgebraicExpression.h"
string infix2postfix(const string exp){
stack<char> opStack;
string postfix;
for(char c : exp){
if(isDigit(c)){
postfix += c;
}
else if (c == '('){
opStack.push(c);
}
else if (c == ')'){
while(!opStack.empty() && opStack.top() != '('){
postfix += opStack.top();
opStack.pop();
}
opStack.pop();
}
else if(c == '*' || c == '/' || c == '+' || c == '-'){
while (!opStack.empty() && precedence(opStack.top()) >= precedence(c)) {
postfix += opStack.top();
opStack.pop();
}
opStack.push(c);
}
}
while (!opStack.empty()) {
postfix += opStack.top();
opStack.pop();
}
return postfix;
}
double evaluatePostfix(const string exp){
stack<double> operandStack;
const int ASCII = 48;
for(char c : exp){
if(isDigit(c)){
operandStack.push(c - ASCII);
}
else if (c == '*' || c == '/' || c == '+' || c == '-'){
double operand2 = operandStack.top();
operandStack.pop();
double operand1 = operandStack.top();
operandStack.pop();
if(c == '*'){
operandStack.push(operand1 * operand2);
}
else if (c == '/'){
operandStack.push(operand1 / operand2);
}
else if (c == '+'){
operandStack.push(operand1 + operand2);
}
else if (c == '-'){
operandStack.push(operand1 - operand2);
}
}
}
return operandStack.top();
}
int precedence(char op){
if(op == '*' || op == '/'){
return 2;
}
else if (op == '+' || op == '-'){
return 1;
}
else{
return 0;
}
}
bool isDigit(const char ch){
if (ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9' )
return true;
else
return false;
}