-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInFixToPostFix.java
More file actions
58 lines (51 loc) · 1.49 KB
/
InFixToPostFix.java
File metadata and controls
58 lines (51 loc) · 1.49 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
package com.company;
import java.util.Stack;
public class InFixToPostFix {
static int prec(char ch){
switch(ch){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static String InfixToPostfix(String string){
String str = "";
Stack<Character> stack = new Stack<>();
for(int i=0; i<string.length(); i++){
char ch = string.charAt(i);
if(Character.isLetterOrDigit(ch)){
str += Character.toString(ch);
}
else if (ch == '('){
stack.push(ch);
}
else if (ch == ')'){
while(!stack.isEmpty() && stack.peek() != '(')
str += stack.pop();
stack.pop();
}
else {
while (!stack.isEmpty() && prec(ch) <= prec(stack.peek())) {
str += stack.pop();
}
stack.push(ch);
}
}
while(!stack.isEmpty()){
if(stack.peek() == '(')
return "Invalid Expression";
str += stack.pop();
}
return str;
}
public static void main(String[] args) {
String s = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(InfixToPostfix(s));
}
}