-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem2.java
95 lines (74 loc) · 1.6 KB
/
Problem2.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
package Stack;
import java.util.Arrays;
import java.util.Stack;
public class Problem2 {
public static void main(String[] args) {
String exp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(infixToPostfix(exp));
}
private static String infixToPostfix(String exp) {
Stack<Character> s = new Stack();
String result="";
for(int i=0;i<exp.length();i++){
char c=exp.charAt(i);
if(c>='a' && c<='z')
result+=c;
else if(c=='(')
s.push(c);
else if(c==')'){
System.out.println("before::"+s);
while(!s.isEmpty() && s.peek()!='('){
result+=s.pop();
}
System.out.println("after::"+s);
if(!s.isEmpty() &&s.peek()!='(')
return "invalid operation";
else
s.pop();
System.out.println("after that::"+s);
}
else
{
while(!s.isEmpty() && (prec(c)<=prec(s.peek()))){
result+=s.pop();
}
s.push(c);
}}
while(!s.isEmpty()){
result+=s.pop();
}
return result;
}
private static int prec(char c) {
switch(c){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
/*private char pop(Stack s) {
if(isEmpty(s))
{
System.out.println("Underflow");
return '1';
}
else
return arr[s.top1--];
}
private void push(Stack s,char i) {
if(s.top1>=(MAX-1))
System.out.println("Overflow");
else{
arr[++s.top1]=i;
}
}
private boolean isEmpty(Stack s) {
return (s.top1<0?true:false);
}*/
}