forked from imnishant/GeeksforGeeks-Java-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfix-To-Postfix
67 lines (64 loc) · 1.63 KB
/
Infix-To-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
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int prec(char ch)
{
switch(ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default: return -1;
}
}
static void infixToPostfix(char c[])
{
String s = "";
Stack<Character> st = new Stack<Character>();
for(int i=0 ; i<c.length ; i++)
{
if(Character.isLetterOrDigit(c[i]))
s += c[i];
else if(c[i] == '(')
st.push(c[i]);
else if(c[i] == ')')
{
while(!st.isEmpty() && st.peek() != '(')
s += st.pop();
if(st.isEmpty())
{
continue;
}
st.pop();
}
else
{
while(!st.isEmpty() && prec(c[i]) <= prec(st.peek()) && st.peek() != '(')
{
s += st.pop();
}
st.push(c[i]);
}
}
while(!st.isEmpty())
s += st.pop();
System.out.println(s);
}
public static void main (String[] args) throws Exception
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
while(t-- > 0)
{
char c[] = bf.readLine().trim().toCharArray();
infixToPostfix(c);
}
}
}