-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ4.cpp
More file actions
65 lines (56 loc) · 1.48 KB
/
Copy pathQ4.cpp
File metadata and controls
65 lines (56 loc) · 1.48 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
#include <iostream>
#include <stack>
#include <cctype> // for isalpha and isdigit
using namespace std;
// function to return precedence of operators
int precedence(char op) {
if (op == '^') return 3;
if (op == '*' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}
string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";
for (int i = 0; i < infix.length(); i++) {
char ch = infix[i];
// if operand, add to postfix
if (isalnum(ch)) {
postfix += ch;
}
// if (, push
else if (ch == '(') {
s.push(ch);
}
// if ), pop till (
else if (ch == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
if (!s.empty()) s.pop(); // remove '('
}
// operator
else {
while (!s.empty() && precedence(s.top()) >= precedence(ch)) {
postfix += s.top();
s.pop();
}
s.push(ch);
}
}
// pop remaining
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
string infix;
cout << "Enter an infix expression: ";
cin >> infix;
string postfix = infixToPostfix(infix);
cout << "Postfix expression: " << postfix << endl;
return 0;
}