-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfix.java
More file actions
67 lines (60 loc) · 1.88 KB
/
Copy pathInfixToPostfix.java
File metadata and controls
67 lines (60 loc) · 1.88 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
63
64
65
66
67
package project;
public class InfixToPostfix {
private Stack stack;
public InfixToPostfix(int stackSize) {
this.stack = new Stack(stackSize);
}
private int getPrecedence(char operator) {
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
public String convertToPostfix(String infix) {
stack = new Stack(infix.length()); // initialize stack
StringBuilder postfix = new StringBuilder();
int i = 0;
while (i < infix.length()) {
char ch = infix.charAt(i);
if (Character.isLetterOrDigit(ch)) {
postfix.append(ch);
}
else if (ch == '(') {
stack.push(ch);
}
else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append((char)stack.pop());
}
if (!stack.isEmpty() && stack.peek() == '(') {
stack.pop();
}
else {
return "Invalid Expression";
}
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^') {
while (!stack.isEmpty() && stack.peek() != '(' && getPrecedence((char)stack.peek()) >= getPrecedence(ch)) {
postfix.append((char)stack.pop());
}
stack.push(ch);
}
i++;
}
while (!stack.isEmpty()) {
if (stack.peek() == '(') {
return "Invalid Expression";
}
postfix.append((char)stack.pop());
}
return postfix.toString();
}
}