-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfixToPostfix.java
58 lines (58 loc) · 1.12 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
import java.util.*;
public class InfixToPostfix {
char stack[]; int top;
InfixToPostfix(int n){
stack=new char[n];
top=-1;
}
String post(String s) {
char c[]=s.toCharArray();
String n="";
for(char i:c) {
if(Character.isLetterOrDigit(i))
n+=i;
else if(i=='(')
push(i);
else if(i==')') {
while(top!=-1 && stack[top]!='(') {
n+=pop();
}
pop();
}
else {
while(top!=-1 && prec(i)<=prec(stack[top])) {
n+=pop();
}
push(i);
}
}
while(top!=-1) {
if(stack[top]=='(')
return "Invalid";
n+=pop();
}
return n;
}
void push(char c) {
stack[++top]=c;
}
char pop() {
return stack[top--];
}
int prec(char c) {
if("+-".indexOf(c+"")>-1)
return 1;
else if("*%/".indexOf(c+"")>-1)
return 2;
else if(c=='^')
return 3;
else
return -1;
}
public static void main(String args[]) {
System.out.println("Enter an expression");
String s=new Scanner(System.in).next();
InfixToPostfix ob =new InfixToPostfix(s.length());
System.out.println("The postfix expression is:"+ob.post(s));
}
}