-
Notifications
You must be signed in to change notification settings - Fork 0
/
in2Pj
75 lines (63 loc) · 1.78 KB
/
in2Pj
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
import java.util.StringTokenizer;
public class InfixToPostFix {
private boolean checkOperator(String op) {
if (op.equals("x") || op.equals("/") || op.equals("-") || op.equals("+")) {
// Return true if operator.
return true;
} else {
// Return false if operand.
return false;
}
}
// Precedence order -: ~,# > *,/ > +,- > (
// ~ is unary minus and # is unary plus.
private int checkPrecedence(String operator) {
if (operator.equals("+") || operator.equals("-")) {
return 1;
} else {
return 2;
}
}
public String In2pJ(String Infix, Queue queue) {
Stack stack = new Stack();
StringTokenizer st = new StringTokenizer(Infix, "*/+-", true);
while (st.hasMoreTokens()) {
String token = st.nextToken();
boolean retVal = checkOperator(token);
if (retVal) { // operator
int precedence = checkPrecedence(token);
String stackToken = stack.pop();
while (stackToken != null) {
int stackPrecedence = checkPrecedence(stackToken);
if (stackPrecedence > precedence) {
queue.enqueue(stackToken);
} else {
stack.push(stackToken);
break;
}
stackToken = stack.pop();
}
stack.push(token);
} else {// operand
queue.enqueue(token);
}
}
String stackToken = stack.pop();
while (stackToken != null) {
queue.enqueue(stackToken);
stackToken = stack.pop();
}
String postFix = "";
String queueToken = queue.dequeue();
while (queueToken != null) {
postFix = postFix + queueToken;
queueToken = queue.dequeue();
}
return postFix;
}
public static void main(String args[]) {
InfixToPostFix infixToPostfix = new InfixToPostFix();
Queue queue = new Queue();
System.out.println("Enter String :" + args[0]);
System.out.println("Postfix :" + infixToPostfix.In2pJ(args[0], queue));
}