-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfixToSuffix.cpp
54 lines (52 loc) · 1.39 KB
/
infixToSuffix.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
//
// Created by FanBig on 2023/3/15.
//
#include "infixToSuffix.h"
std::string infixToSuffix::toSuffix(const std::string &expression, myPrecede mp) {
std::stack<char> sta;
std::string str;
for (char ch: expression) {
switch (ch) {
case '!':
case '^':
case '+':
case '-':
case '*':
case '/': {
if (sta.empty()) {
sta.push(ch);
} else {
if (mp.Precede(ch) > mp.Precede(sta.top())) {
sta.push(ch);
} else {
while (!sta.empty() && mp.Precede(sta.top()) >= mp.Precede(ch)) {
str += sta.top();
sta.pop();
}
sta.push(ch);
}
}
break;
}
case '(':
sta.push(ch);
break;
case ')': {
while (!sta.empty() && sta.top() != '(') {
str += sta.top();
sta.pop();
}
sta.pop();
break;
}
default:
str += ch;
break;
}
}
while (!sta.empty()) {
str += sta.top();
sta.pop();
}
return str;
}