Repository navigation
Expand file tree
/
Copy pathInfix_To_Postfix.cpp
More file actions
66 lines (57 loc) · 1.52 KB
/
Copy pathInfix_To_Postfix.cpp
File metadata and controls
66 lines (57 loc) · 1.52 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
#include <iostream>
#include <stack>
#include <cctype>
using namespace std;
int precedence(char op) {
if (op == '^') return 3;
if (op == '*' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}
string toPostfix(const string& infix) {
stack<char> ops;
string postfix;
for (size_t i = 0; i < infix.length(); ++i) {
char c = infix[i];
if (isdigit(c)) {
// Extract full number
while (i < infix.length() && isdigit(infix[i])) {
postfix += infix[i++];
}
postfix += ' ';
i--; // adjust loop index
}
else if (c == '(') {
ops.push(c);
}
else if (c == ')') {
while (!ops.empty() && ops.top() != '(') {
postfix += ops.top(); postfix += ' ';
ops.pop();
}
if (!ops.empty()) ops.pop(); // remove '('
}
else {
while (!ops.empty() && precedence(ops.top()) >= precedence(c)) {
postfix += ops.top(); postfix += ' ';
ops.pop();
}
ops.push(c);
}
}
// Flush remaining operators
while (!ops.empty()) {
postfix += ops.top(); postfix += ' ';
ops.pop();
}
return postfix;
}
int main() {
string infix;
cout << "Enter infix expression: ";
cin >> infix;
string postfix = toPostfix(infix);
cout << "Postfix Expression: " << postfix << endl;
return 0;
}
//12*5+(20/5)