-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathinfixToPostfixUsingStack.cpp
77 lines (68 loc) · 1.53 KB
/
infixToPostfixUsingStack.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
// C++ implementation to convert infix expression to postfix
#include<bits/stdc++.h>
using namespace std;
int pc(char ch){
switch(ch){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
case '(':
return -1;
}
}
// The main function to convert infix expression
//to postfix expression
string infixToPostfix(string s)
{
string g="";
int j=-1;
stack< char >p;
p.push('(');
s+=')';
for(int i=0;i<s.length();i++){
if(s[i]>=65 && s[i]<=90 || s[i]>=97 && s[i]<=122 ){
g+=s[i];
}
else if(s[i]=='('){
p.push(s[i]);
}
else if (s[i]==')'){
while(p.top()!='('){
g+=p.top();
p.pop();
}
p.pop();
}
else{
while(!p.empty() && pc(p.top())>=pc(s[i])){
char c=p.top();
p.pop();
g+=c;
}
p.push(s[i]);
}
}
return g;
// Your code here
}
// { Driver Code Starts.
//Driver program to test above functions
int main()
{
int t;
cin>>t;
cin.ignore(INT_MAX, '\n');
while(t--)
{
string exp;
cin>>exp;
cout<<infixToPostfix(exp)<<endl;
}
return 0;
}
// } Driver Code Ends