-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathItoP2
More file actions
73 lines (67 loc) · 1.61 KB
/
Copy pathItoP2
File metadata and controls
73 lines (67 loc) · 1.61 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
72
73
package bubs;
import java.util.*;
import java.io.*;
public class ItoP { // infix to postfix
int prec(char c) {
//it gives precedence of mathematical operator like bodmas rule
if(c=='^') {
return 3; //highest precedence
}
else if(c=='/' || c =='*') {
return 2;
}
else if(c == '+' || c =='-') {
return 1;
}
else {
return -1;
}
}
String Infixtopostfix(String f){
String output = ""; //postfix string
String s= "";
Stack<String> op = new Stack<String>();
char c;
char ch;
String fix = f;
String postfix = "";
for(int i=0;i<fix.length();i++) {
c = fix.charAt(i);
if(c != '+' && c != '-' && c != '%'&& c != '/' && c != '+'&& c != '*' && c != '+'&& c != '(' && c != ')') {
postfix = postfix + c;
}
// if operator is scanned
else if(c == '+' || c == '-' || c == '%'|| c == '/' || c == '+'|| c == '*' || c == '+'|| c == '(' || c == ')') {
//logic with precedence
//op.push(c+"");
while(!op.isEmpty() && prec(c) < prec(op.peek())) {
output = output + op.pop();
}
op.push(c);
}
else if(c == ')') {
ch=op.pop(); //take out top element from stack
if(!ch.equals('(')) {
output = output + s;
}
}
else {
System.out.println("khali hai");
}
}
System.out.println("Output :"+output);
return output;
}
public static void main(String[] args) {
ItoP p = new ItoP();
try {
Scanner sc = new Scanner(System.in);
String expression = sc.nextLine();
String postfix = p.Infixtopostfix(expression);
System.out.println("The postfix expression is :"+postfix);
}
catch(Exception e) {
e.printStackTrace();
}
}
}