-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathInfixToPrefix.cpp
102 lines (75 loc) · 1.51 KB
/
InfixToPrefix.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
#include<iostream>
#include<stack>
using namespace std;
/*Algorithm-
1) Reverse the given infix expression.
2) Obtain the postfix expression of the modified infix expression.
3) Now reverse the postfix expression obtained, which will give us the Prefix expression.
*/
bool isOperator(char c)
{
return (!isdigit(c) && !isalpha(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 len = infix.size();
string output;
stack<char>s;
for(int i = 0 ; i < len; i++)
{
//if operand-add it to the postfix expression
if(isalpha(infix[i]) || isdigit(infix[i]))
output += infix[i];
//if opening brace then push it to stack
else if(infix[i]=='(')
s.push(infix[i]);
else if(infix[i]==')')
{
while(!s.empty() && s.top() != '(')
{
output += s.top();
s.pop();
}
//remove ( from stack
s.pop();
}
//if operator is found
else
{
if(isOperator(infix[i]))
{
while(!s.empty() && getPriority(infix[i]) <= getPriority(s.top()))
{
output += s.top();
s.pop();
}
//push current lower priority operator on stack
s.push(infix[i]);
}
}
}
//if remaining elements in stack, make it empty
while(!s.empty())
{
output += s.top();
s.pop();
}
return output;
}
int main()
{
string s= InfixToPostfix("(a-b/c)*(a/k-l)");
cout<<s;
return 0;
}