-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLabCycle2-8.cpp
69 lines (58 loc) · 1.61 KB
/
LabCycle2-8.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
#include "LabCycle2-8.h"
#include <stack>
#include <algorithm>
template<typename T>
bool isOperator(T c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
template<typename T>
int precedence(T op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
template<typename T>
string infixToPostfix(const string& infix) {
stack<T> operators;
string postfix = "";
for (T c : infix) {
if (isalnum(c)) {
postfix += c;
} else if (c == '(') {
operators.push(c);
} else if (c == ')') {
while (!operators.empty() && operators.top() != '(') {
postfix += operators.top();
operators.pop();
}
operators.pop();
} else {
while (!operators.empty() && precedence(operators.top()) >= precedence(c)) {
postfix += operators.top();
operators.pop();
}
operators.push(c);
}
}
while (!operators.empty()) {
postfix += operators.top();
operators.pop();
}
return postfix;
}
template<typename T>
string infixToPrefix(const string& infix) {
string reversedInfix = infix;
reverse(reversedInfix.begin(), reversedInfix.end());
for (T& c : reversedInfix) {
if (c == '(')
c = ')';
else if (c == ')')
c = '(';
}
string postfix = infixToPostfix<T>(reversedInfix);
reverse(postfix.begin(), postfix.end());
return postfix;
}