-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q1_infix_calculator.cpp
134 lines (126 loc) · 3.01 KB
/
Q1_infix_calculator.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
128
129
130
131
132
133
134
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
#define dt double;
template <class gt>
struct SNode {
SNode<gt> *next;
gt num;
};
template <class gt>
class MyStack {
private:
SNode<gt> *topNode;
long size;
public:
MyStack<gt>() {
topNode = NULL;
size = 0;
}
int isEmpty() {
if(topNode == NULL)
return 1;
return 0;
}
void push(gt x) {
SNode<gt> *node = new SNode<gt>;
node->num = x;
node->next = topNode;
topNode = node;
size++;
}
void pop() {
if(!isEmpty()) {
topNode = topNode->next;
size--;
}
}
int getSize() {
return size;
}
gt getTop() {
if(!isEmpty())
return topNode->num;
return (gt)NULL;
}
};
MyStack<char> opt_stack;
MyStack<double> num_stack;
void calculate(char x) {
double b = num_stack.getTop();
num_stack.pop();
double a = num_stack.getTop();
num_stack.pop();
if(x=='+')
num_stack.push(a+b);
else if(x=='-')
num_stack.push(a-b);
else if(x=='*')
num_stack.push(a*b);
else if(x=='/')
num_stack.push((double)a/b);
else if(x=='%')
num_stack.push((double)fmod(a,b));
else if(x=='^')
num_stack.push(pow(a,b));
}
int priority(char p) {
if(p=='+' || p=='-')
return 1;
if(p=='*' || p=='/' || '%')
return 2;
if(p=='^')
return 3;
return 0;
}
int main() {
string str, temp="";
cin >> str;
long i=0;
while(i < (long)str.length()) {
if(isdigit(str[i])) {
while (isdigit(str[i]) || str[i] == '.') {
temp += str[i];
i++;
}
if (temp != "") {
num_stack.push(stod(temp));
temp = "";
}
}
else if(str[i]=='(') {
opt_stack.push(str[i]);
i++;
}
else if(str[i]==')') {
while(opt_stack.getSize()>0 && opt_stack.getTop()!='(') {
calculate(opt_stack.getTop());
opt_stack.pop();
}
opt_stack.pop();
i++;
}
else {
if(opt_stack.getSize()==0 || opt_stack.getTop()=='(')
opt_stack.push(str[i]);
else if((opt_stack.getTop()=='^' && str[i]=='^' ) || (priority(str[i]) > priority(opt_stack.getTop()))) {
opt_stack.push(str[i]);
}
else {
while(!opt_stack.isEmpty() && (priority(opt_stack.getTop()) >= priority(str[i])) && opt_stack.getTop()!='(') {
calculate(opt_stack.getTop());
opt_stack.pop();
}
opt_stack.push(str[i]);
}
i++;
}
}
while(!opt_stack.isEmpty()) {
calculate(opt_stack.getTop());
opt_stack.pop();
}
cout << fixed << setprecision(5) << num_stack.getTop() << endl;
return 0;
}