-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixTOprefixConvertion.cpp
110 lines (94 loc) · 2.33 KB
/
InfixTOprefixConvertion.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <bits/stdc++.h>
using namespace std;
bool isOperator(char c)
{
return (!isalpha(c) && !isdigit(c));
}
int getPriority(char C)
{
if (C == '-' || C == '+')
return 1;
else if (C == '*' || C == '/')
return 2;
else if (C == '^')
return 3;
return 0;
}
string infixToPostfix(string infix)
{
infix = '(' + infix + ')';
int l = infix.size();
stack<char> st;
string v;
for (int i = 0; i < l; i++) {
if (isalpha(infix[i]) || isdigit(infix[i]))
v += infix[i];
else if (infix[i] == '(')
st.push('(');
else if (infix[i] == ')') {
while (st.top() != '(')
{
v += st.top();
st.pop();
}
st.pop();
}
else {
if (isOperator(st.top()))
{
while (getPriority(infix[i]) <= getPriority(st.top()))
{
v += st.top();
st.pop();
}
st.push(infix[i]);
}
}
}
return v;
}
string infixToPrefix(string infix)
{
int l = infix.size();
reverse(infix.begin(), infix.end());
for (int i = 0; i < l; i++) {
if (infix[i] == '(') {
infix[i] = ')';
}
else if (infix[i] == ')') {
infix[i] = '(';
}
}
string prefix = infixToPostfix(infix);
reverse(prefix.begin(), prefix.end());
return prefix;
}
int main()
{
while (1)
{
cout << "1.Infix to Prefix. 2.Infi1x to POSTFIX.\n3.Exit\nSELECT NUMBER : ";
int ch;
scanf("%d", &ch);
if (ch == 1)
{
string str;
printf("Infix Expression : ");
cin >> str;
cout <<"Prefix Expression="<< infixToPrefix(str) <<endl ;
}
else if (ch == 2)
{
string exp;
printf("Infix Expression : ");
cin >> exp;
cout <<"Postfix Expression="<< infixToPostfix(exp) <<endl ;
}
else if (ch == 3)
break;
}
}
// # (A+B)*(C+D)
// A+(B*C) (a+(((c*f)-d)*e)+(b*c)+(q-(r/g)))
// (((A/B)+(B*C))-E)
// (A+((B*C)/(E-F)))