-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathinfixTopostfix.java
More file actions
96 lines (78 loc) · 2.01 KB
/
Copy pathinfixTopostfix.java
File metadata and controls
96 lines (78 loc) · 2.01 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.util.*;
public class infixTopostfix {
int sp;
char ch[];
int i;
infixTopostfix(int n) {
ch = new char[n];
sp = -1;
}
void convert(char c[]) {
char result[] = new char[c.length];
int k = 0;
char s, s2;
for (i = 0; i < c.length; i++) {
s = c[i];
if (check(s)) {
result[k++] = s;
} else {
while (sp != -1 && (order(s) <= order(ch[sp])) && s != '(') {
s2 = pop();
if (s2 == '(') {
break;
} else if (s2 != '(') {
result[k++] = s2;
}
}
if (s != ')') {
push(s);
}
}
}
while (sp != -1) {
result[k++] = pop();
}
for (i = 0; i < k; i++) {
if (result[i] != '(' && result[i] != ')') {
System.out.print(result[i]);
}
}
}
boolean check(char p) {
return ((p >= '0' && p <= '9') || (p >= 'a' && p <= 'z') || (p >= 'A' && p <= 'Z'));
}
int order(char t) {
switch (t) {
case '(':
case ')':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '$':
return 3;
default:
System.out.println("invalid");
return (-1);
}
}
void push(char a) {
sp++;
ch[sp] = a;
}
char pop() {
return (ch[sp--]);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the expression");
String expre;
expre = in.next();
char cc[] = expre.toCharArray();
infixTopostfix ob = new infixTopostfix(cc.length);
ob.convert(cc);
}
}