-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfixExpression.java
More file actions
71 lines (62 loc) · 2.03 KB
/
Copy pathPostfixExpression.java
File metadata and controls
71 lines (62 loc) · 2.03 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
68
69
70
71
import java.util.*;
public class PostfixExpression {
public static void main(String[] args) {
String infix= "9-(5+3)*4/6";
System.out.println("Infix expression: " + infix);
Stack<String> val= new Stack<>();
Stack<Character> op= new Stack<>();
for(int i=0; i<infix.length(); i++){
char ch= infix.charAt(i);
int ascii= (int)ch;
if(ascii>=48 && ascii<=57){
String s= ""+ ch;
val.push(s);
}
else if(ch=='(' || op.size()==0 || op.peek()=='('){
op.push(ch);
}
else if(ch==')'){
while(op.peek()!='('){
String v2= val.pop();
String v1= val.pop();
char o= op.pop();
String temp= v1+v2+o;
val.push(temp);
}
op.pop();
}
else{
if (ch == '+' || ch=='-'){
String v2= val.pop();
String v1= val.pop();
char o= op.pop();
String temp= v1+v2+o;
val.push(temp);
op.push(ch);
}
if (ch=='*' || ch=='/'){
if(op.peek()=='*' || op.peek()=='/'){
String v2= val.pop();
String v1= val.pop();
char o= op.pop();
String temp= v1+v2+o;
val.push(temp);
op.push(ch);
}
else{
op.push(ch);
}
}
}
}
while(val.size()>1){
String v2= val.pop();
String v1= val.pop();
char o= op.pop();
String temp= v1+v2+o;
val.push(temp);
}
String postfix= val.pop();
System.out.println("Postfix expression: " + postfix);
}
}