-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path02.Infix2Prefix.cpp
More file actions
78 lines (69 loc) · 1.97 KB
/
02.Infix2Prefix.cpp
File metadata and controls
78 lines (69 loc) · 1.97 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
#include <bits/stdc++.h>
using namespace std;
int prec(char c) {
if (c == '^') return 3;
if (c == '*' || c == '/') return 2;
if (c == '+' || c == '-') return 1;
return -1;
}
string infixToPrefix(string s) {
// 1) reverse the string
reverse(s.begin(), s.end());
// 2) swap parentheses
for (char &ch : s) {
if (ch == '(') ch = ')';
else if (ch == ')') ch = '(';
}
stack<char> st;
string out;
for (char ch : s) {
if (isspace(static_cast<unsigned char>(ch))) continue;
// operand
if (isalnum(static_cast<unsigned char>(ch))) {
out += ch;
}
// left parenthesis (which was ')' before swap)
else if (ch == '(') {
st.push(ch);
}
// right parenthesis (which was '(' before swap)
else if (ch == ')') {
while (!st.empty() && st.top() != '(') {
out += st.top();
st.pop();
}
if (st.empty()) return "Invalid Expression"; // mismatched
st.pop(); // discard '('
}
// operator
else {
while (!st.empty() && st.top() != '(') {
int pc = prec(ch), pt = prec(st.top());
// KEY: pop on higher precedence, or equal precedence when ch == '^'
if (pt > pc || (pt == pc && ch == '^')) {
out += st.top();
st.pop();
} else break;
}
st.push(ch);
}
}
// pop remaining operators
while (!st.empty()) {
if (st.top() == '(' || st.top() == ')')
return "Invalid Expression";
out += st.top();
st.pop();
}
// 4) reverse the postfix-result to get prefix
reverse(out.begin(), out.end());
return out;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
getline(cin, s);
cout << "Prefix: " << infixToPrefix(s) << "\n";
return 0;
}