-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_expression.cpp
More file actions
96 lines (95 loc) · 1.95 KB
/
stack_expression.cpp
File metadata and controls
96 lines (95 loc) · 1.95 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
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
#include<iostream>
#include<string>
#include<cassert>
using namespace std;
template<class Type> class Stack {
private:
Type *urls;
int max_size, top_index;
public:
Stack(int length_input) {
urls = new Type[length_input];
max_size = length_input;
top_index = -1;
}
~Stack() {
delete[] urls;
}
bool push(const Type &element) {
if (top_index >= max_size - 1) {
return false;
}
top_index++;
urls[top_index] = element;
return true;
}
bool pop() {
if (top_index < 0) {
return false;
}
top_index--;
return true;
}
Type top() {
assert(top_index >= 0);
return urls[top_index];
}
bool empty() {
if (top_index < 0) {
return true;
} else {
return false;
}
}
};
bool precede(char a, char b) {
if (a == '*') {
return true;
} else {
return false;
}
}
int operate(char theta, int a, int b) {
if (theta == '+') {
return a + b;
} else {
return a * b;
}
}
void calc(Stack<int> &numbers, Stack<char> &operators) {
int a = numbers.top();
numbers.pop();
int b = numbers.top();
numbers.pop();
numbers.push(operate(operators.top(),a,b));
operators.pop();
}
int main() {
int n;
cin>>n;
Stack<int>numbers(n);
Stack<char>operators(n);
string buffer;
cin>>buffer;
int i = 0;
while(i < n){
if(isdigit(buffer[i])){
numbers.push(buffer[i] - '0');
i++;
}
else{
if(operators.empty() || precede(buffer[i],operators.top())){
operators.push(buffer[i]);
i++;
}
else{
calc(numbers,operators);
}
}
}
while(!operators.empty()){
calc(numbers,operators);
}
cout<<numbers.top()<<endl;
return 0;
}