-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack-prefix.cpp
More file actions
70 lines (46 loc) · 1.18 KB
/
stack-prefix.cpp
File metadata and controls
70 lines (46 loc) · 1.18 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
#include<iostream>
#include<string>
#define n 10
using namespace std;
class Stack {
public:
int *arr = new int[n];
int top = -1;
void push(int data) {
top++;
arr[top] = data;
}
void pop() {
top--;
}
int Top() {
return arr[top];
}
};
int infixEvaluation(string infix) {
Stack disk;
int operator1;
int operator2;
for(int i = infix.length() - 1; i >= 0; i--) {
if(infix[i] >= '0' && infix[i] <= '9') {
disk.push( int(infix[i]) - int('0'));
} else {
operator1 = disk.Top();
disk.pop();
operator2 = disk.Top();
disk.pop();
switch(infix[i]) {
case '+': disk.push(operator1 + operator2); break;
case '-': disk.push(operator1 - operator2); break;
case '*': disk.push(operator1 * operator2); break;
case '/': disk.push(operator1 / operator2); break;
}
}
}
return disk.Top();
}
int main() {
string infix = "-+7*45+20";
cout << infixEvaluation(infix);
return 0;
}