-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathinfixPostfix.java
148 lines (117 loc) · 2.57 KB
/
infixPostfix.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import java.util.Scanner;
class Stack {
private Character[] a;
private int ele;
private int size;
public Stack(int size) {
a = new Character[size];
this.size = size;
ele = -1;
}
public void push(Character ch) {
if (isFull()) {
System.out.println("Stack is full");
} else {
ele++;
a[ele] = ch;
}
}
public Character top() {
if (isEmpty()) {
return '#';
} else {
return a[ele];
}
}
public Character pop() {
if (isEmpty()) {
return '#';
} else {
return a[ele--];
}
}
private boolean isEmpty() {
if(ele == -1) return true;
else return false;
}
private boolean isFull() {
if(ele == size - 1) return true;
return false;
}
public void display() {
for(int i=0; i<=ele; i++)
System.out.print(a[i] + " ");
System.out.println();
}
}
class infixPostfix {
private Character[] oprator;
public infixPostfix() {
oprator = new Character[]{'+', '-', '*', '/'};
}
public static void main(String[] args) {
infixPostfix ip = new infixPostfix();
Scanner sc = new Scanner(System.in);
System.out.println("Enter Infix expression");
String infix = sc.nextLine();
String postfix = ip.convert(infix);
// String postfix = ip.convert("a*(b+c)-d/(e+f)");
// String postfix = ip.convert("a+b-(c*d/f-g)");
System.out.println(postfix);
}
public String convert(String exp) {
int expLen = exp.length();
Stack s = new Stack(expLen);
String postfix = "";
for(int i=0; i < expLen; i++) {
if( exp.charAt(i) == '(' ) {
s.push('(');
} else if( eleExist(exp.charAt(i)) ) {
Character top = s.top();
if( eleExist (top)) {
int didPopStackTop = 0;
while( eleExist(top) ) {
int p1 = opPriority(top);
int p2 = opPriority(exp.charAt(i));
if( p1 < p2 ) {
s.push(exp.charAt(i));
break;
} else {
postfix += s.pop();
top = s.top();
didPopStackTop = 1;
}
}
if( didPopStackTop == 1 ) s.push(exp.charAt(i));
} else {
s.push(exp.charAt(i));
}
} else if( exp.charAt(i) == ')' ) {
while (true) {
Character ch = s.pop();
if(ch == '(') break;
postfix += ch;
}
} else {
postfix += exp.charAt(i);
}
}
while(true) {
Character ch = s.pop();
if( ch == '#') { break; }
postfix += ch;
}
return postfix;
}
private int opPriority(Character ch) {
if(ch == '+' || ch == '-') return 1;
if(ch == '*' || ch == '/') return 2;
return 0;
}
private boolean eleExist(Character c) {
for(int i=0; i<oprator.length; i++) {
if(oprator[i] == c) return true;
}
return false;
}
}