-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixtoPostfix.cpp
82 lines (75 loc) · 1.86 KB
/
InfixtoPostfix.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
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
int precedence(char c)
{
if (c == '^')
return 3;
else if (c == '*' || c == '/')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
string infixToPostPrefix(string infix, bool toPrefix = false)
{
stack<char> s;
string fix;
if (toPrefix)
{
reverse(infix.begin(), infix.end());
}
for (char c : infix)
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
fix += c;
}
else if ((!toPrefix && c == '(') || (toPrefix && c == ')'))
{
s.push(c);
}
else if ((!toPrefix && c == ')') || (toPrefix && c == '('))
{
while (!toPrefix && !s.empty() && s.top() != '(' || toPrefix && !s.empty() && s.top() != ')')
{
fix += s.top();
s.pop();
}
if (!toPrefix && !s.empty() && s.top() == '(' || toPrefix && !s.empty() && s.top() == ')')
s.pop();
}
else
{
while (!s.empty() && precedence(c) <= precedence(s.top()))
{
fix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty())
{
fix += s.top();
s.pop();
}
if (toPrefix)
{
reverse(fix.begin(), fix.end());
}
return fix;
}
int main()
{
string infix, postfix, prefix;
cout << "Enter Infix Expression: ";
cin >> infix;
postfix = infixToPostPrefix(infix, false);
cout << "Postfix Expression: " << postfix << endl;
prefix = infixToPostPrefix(infix, true);
cout << "Prefix Expression: " << prefix << endl;
return 0;
}