forked from NiharRanjan53/HacktoberFest_2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
infix to Postfix Conversion.cpp
66 lines (61 loc) · 1.48 KB
/
infix to Postfix Conversion.cpp
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<cstdio>
#include<cmath>
#include<stack>
using namespace std;
int isOperand(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (isdigit(ch));
}
int checkPrecedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
int infixToPostfix(char exp[], char output[]) {
int i = 0, k = 0;
stack < char > st;
while (exp[i]) {
if (isOperand(exp[i]))
output[k++] = exp[i];
else if (exp[i] == '(')
st.push(exp[i]);
else if (exp[i] == ')') {
while (!st.empty() && st.top() != '(') {
output[k++] = st.top();
st.pop();
}
if (!st.empty() && st.top() != '(')
return -1;
else
st.pop();
} else {
while (!st.empty() && checkPrecedence(exp[i]) <= checkPrecedence(st.top())) {
output[k++] = st.top();
st.pop();
}
st.push(exp[i]);
}
i++;
}
while (!st.empty()) {
output[k++] = st.top();
st.pop();
}
output[k++] = '\0';
}
int main() {
char exp[] = "6/(3^2)-8";
char output[20];
infixToPostfix(exp, output);
cout << "Given infix expression is : " << exp << endl;
cout << "Equivalent postfix expression is : " << output << endl;
return 0;
}