-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path06.Prefix2Postfix.cpp
More file actions
58 lines (48 loc) · 1.38 KB
/
06.Prefix2Postfix.cpp
File metadata and controls
58 lines (48 loc) · 1.38 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
#include <bits/stdc++.h>
using namespace std;
bool isOperand(char c) {
return isalnum(static_cast<unsigned char>(c));
}
bool isOperator(char c) {
return c=='+' || c=='-' || c=='*' || c=='/' || c=='^';
}
string prefixToPostfix(const string& s) {
stack<string> st;
int i = static_cast<int>(s.size()) - 1;
while (i >= 0) {
unsigned char ch = static_cast<unsigned char>(s[i]);
if (isspace(ch)) {
--i;
continue;
}
if (isOperand(ch)) {
st.push(string(1, s[i]));
} else if (isOperator(ch)) {
if (st.size() < 2)
throw runtime_error("Invalid expression: insufficient operands for operator.");
string t1 = st.top();
st.pop();
string t2 = st.top();
st.pop();
st.push(t1 + t2 + s[i]);
} else {
throw runtime_error(string("Invalid character in expression: '") + s[i] + "'");
}
--i;
}
if (st.size() != 1)
throw runtime_error("Invalid expression: leftover operands/operators.");
return st.top();
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
getline(cin, s);
try {
cout << "Postfix: " << prefixToPostfix(s) << "\n";
} catch (const exception& e) {
cout << "Error: " << e.what() << "\n";
}
return 0;
}