-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInfixToPostfixExpression.java
More file actions
62 lines (53 loc) · 1.62 KB
/
InfixToPostfixExpression.java
File metadata and controls
62 lines (53 loc) · 1.62 KB
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
package datastructure.stack.program;
import datastructure.stack.Stack;
public class InfixToPostfixExpression {
public static void main(String[] args) throws Exception {
String expression = "2 + 3 * 3 + (2 * 8) / 4 ";
Stack<Character> operatorStack = new Stack<Character>();
char[] charArray = expression.toCharArray();
for (Character c : charArray) {
// if c is empty skip the iteration
if (c == ' ')
continue;
// if c is a number then output it
if (c != '+' && c != '-' && c != '*' && c != '/' && c != '^' && c != '(' && c != ')') {
System.out.print(c + " ");
continue;
}
if (c == '(') {
operatorStack.push(c);
continue;
}
// if c is close parenthesis pop the stack until open parenthesis is
// encountered
if (c == ')') {
while (operatorStack.peek() != '(')
System.out.print(operatorStack.pop() + " ");
operatorStack.pop();
continue;
}
// while c is an operator of less precedence than the operator on
// top of the stack pop the stack until the precedence at the top is
// less than the current operator or null
while (operatorStack.peek() != null && getPrecedence(c) <= getPrecedence(operatorStack.peek()))
System.out.print(operatorStack.pop() + " ");
operatorStack.push(c);
}
while (operatorStack.peek() != null)
System.out.print(operatorStack.pop() + " ");
}
private static int getPrecedence(Character op) throws Exception {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return -1;
}
}
}