forked from ShivamDubey7/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathInfix_2_postfix
96 lines (68 loc) · 2.63 KB
/
Infix_2_postfix
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
#include<iostream>
#include<stack> // in-build stack data structure
using namespace std;
bool is_operator(char c){ //to check if the parameter is an operator
if((c=='+') || (c=='-') || (c=='*') || (c=='/'))
return true;
else
return false;
}
int check_pre(char c){ //precedence function in which precedence of the ( and ) is not considered
if(c=='^') return 3;
else if((c=='*') || (c=='/')) return 2;
else if((c=='+') || (c=='-')) return 1;
else return -1;
}
string in_post(stack<char> s,string infix){
string postfix;
for( int i=0 ; i<infix.length() ; i++){
if(( infix[i] >= 'a' && infix[i]<='z') || ( infix[i] >= 'A' && infix[i] <= 'Z')) //If it is an alpha then we will directly add in postfix
postfix+=infix[i];
else if( infix[i] == '(' ) //If '(' then simply push in stack
s.push(infix[i]);
else if( infix[i] == ')' ){
while ((!s.empty()) && (s.top() != '(')){ //If ')' then pop till '('
postfix+=s.top();
s.pop();
}
if(s.top() == '('){
s.pop();
}
}
else if(is_operator(infix[i])){ //check if it is an operator
if(s.empty()){ //If stack is empty then simply push
s.push(infix[i]);
}
else{
if(check_pre(infix[i]) > check_pre(s.top())) //If precedence is higher then simply push
s.push(infix[i]);
else if(check_pre(infix[i])==check_pre(s.top()) && infix[i]=='^') //Associtivity of exponential is right to left
s.push(infix[i]);
else{
while((!s.empty() && check_pre(infix[i]) <= check_pre(s.top()))){ //pop out till th top has lower precedence
postfix+=s.top();
s.pop();
}
s.push(infix[i]);
}
}
}
}
while(!s.empty()){ //pop everything out till the stack is empty
postfix+=s.top();
s.pop();
}
return postfix;
}
int main(){
string infix,postfix;
cout<<"-----INFIX_to_POSTFIX-------"<<endl;
cout<<"Enter an INFIX expression:";
cin>>infix;
stack <char> s;
cout<<endl;
cout<<"INFIX expression: "<<infix<<endl;
postfix = in_post(s,infix);
cout<<"POSTFIX expression:"<<postfix<<endl;
return 0;
}