This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
forked from abhishekchopra13/nwoc_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 52
/
InfixToPostfix.java
89 lines (74 loc) · 2.43 KB
/
InfixToPostfix.java
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
// InfixToPostfix Conversion
// Language Used: JAVA
// Given an infix expression in the form of a string str. Convert this infix expression to postfix expression.
// Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands.
// Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands.
// Input format: The first line of input contains an integer T denoting the number of test cases. The next T lines contains an infix expression.
// The expression contains all characters and ^,*,/,+,-.
// Output format: For each testcase, in a new line, output the infix expression to postfix expression.
// Sample Input:
// 2 Denoting no. of test cases.
// a+b*(c^d-e)^(f+g*h)-i
// A*(B+C)/D
// Sample Output:
// abcd^e-fgh*+^*+i-
// ABC+*D/
import java.util.*;
class InfixToPostfix{
public static int precision(char operator)
{
switch(operator)
{
case '^':
return 3;
case '/':
case '*':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int testcase = scan.nextInt();
while(testcase -- > 0)
{
String infix = scan.next();
infix+=")";
Stack<Character>stack = new Stack<Character>();
stack.push('(');
String postfix="";
int i=0;
while(!stack.isEmpty())
{
if( infix.charAt(i)=='(' )
stack.push('(');
else if( infix.charAt(i)==')' )
{
while( stack.peek()!='(' )
{
postfix+=stack.pop();
}
stack.pop();
}
else if( Character.isLetter( infix.charAt(i) ) )
{
postfix+=infix.charAt(i);
}
else
{
while( precision(stack.peek()) >= precision( infix.charAt(i) ) )
{
postfix+=stack.pop();
}
stack.push( infix.charAt(i) );
}
i++;
}
System.out.println(postfix);
}
}
}