-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path01.Infix2Postfix.cpp
More file actions
79 lines (70 loc) · 1.94 KB
/
01.Infix2Postfix.cpp
File metadata and controls
79 lines (70 loc) · 1.94 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
#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;
}
bool isLeftAssociative(char c) {
// +, -, *, / are left-associative; ^ is right-associative
return (c != '^');
}
bool isOperand(char c) {
return (isalnum(static_cast<unsigned char>(c))); // A-Z, a-z, 0-9
}
string infixToPostfix(const string& s) {
stack<char> st;
string out;
for (char ch : s) {
if (isspace(static_cast<unsigned char>(ch))) continue; // ignore spaces
if (isOperand(ch)) {
out += ch;
}
else if (ch == '(') {
st.push(ch);
}
else if (ch == ')') {
// pop until '('
while (!st.empty() && st.top() != '(') {
out += st.top();
st.pop();
}
if (st.empty()) {
throw runtime_error("Invalid expression: mismatched parentheses");
}
st.pop(); // discard '('
}
else { // operator
while (!st.empty() && st.top() != '(') {
int pc = prec(ch), pt = prec(st.top());
if (pt > pc || (pt == pc && isLeftAssociative(ch))) {
out += st.top();
st.pop();
} else break;
}
st.push(ch);
}
}
// pop remaining
while (!st.empty()) {
if (st.top() == '(' || st.top() == ')') {
throw runtime_error("Invalid expression: mismatched parentheses");
}
out += st.top();
st.pop();
}
return out;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
getline(cin, s); // allow spaces
try {
cout << "Postfix: " << infixToPostfix(s) << "\n";
} catch (const exception& e) {
cout << "Error: " << e.what() << "\n";
}
return 0;
}