-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPractical_2.1.java
70 lines (61 loc) · 1.74 KB
/
Practical_2.1.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
import java.util.Stack;
class Solution
{
static int Hode(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static String infToPost(String expr)
{
String res = new String("");
Stack<Character> stk = new Stack<>();
for (int i = 0; i<expr.length(); ++i)
{
char c = expr.charAt(i);
if (Character.isLetterOrDigit(c))
res += c;
else if (c == '(')
stk.push(c);
else if (c == ')')
{
while (!stk.isEmpty() && stk.peek() != '(')
res += stk.pop();
if (!stk.isEmpty() && stk.peek() != '(')
return " Expression is not Valid";
else
stk.pop();
}
else
{
while (!stk.isEmpty() && Hode(c) <= Hode(stk.peek())){
if(stk.peek() == '(')
return " Expression is not Valid";
res += stk.pop();
}
stk.push(c);
}
}
while (!stk.isEmpty()){
if(stk.peek() == '(')
return " Expression is not Valid";
res += stk.pop();
}
return res;
}
public static void main(String[] args)
{
String exp = "a+b*(c^d-e)^(f+g*h)-i"; // TEst Case
System.out.println(infToPost(exp));
}
}