-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.java
More file actions
74 lines (70 loc) · 1.89 KB
/
postfix.java
File metadata and controls
74 lines (70 loc) · 1.89 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
import java.util.*;
public class Postfix{
static int precedence(char ch) //function to get the precedence
{
switch(ch){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static String converter(String exp){
String result = new String("");
Stack<Character> sk = new Stack<>();
for(int i=0; i<exp.length(); i++)
{
char c=exp.charAt(i);
if(Character.isLetterOrDigit(c))
{
result=result+c;
}
else if(c=='(')
{
sk.push(c);
}
else if(c==')')
{
while(!sk.isEmpty() && sk.peek() !='(')
{//peek fetches the first element
result = result+sk.pop();
}
if(!sk.isEmpty() && sk.peek() !='(')
{
return("Invalid Expression");
}
else
sk.pop();
}
else
{
while(!sk.isEmpty() && precedence(c) <= precedence(sk.peek()))
{
if(sk.peek() == '(')
{
return "Invalid Expression ";
}
result = result+sk.pop();
}
sk.push(c);
}
}
while(!sk.isEmpty())
{
if(sk.peek() == '(')
return "Invalid Expression";
result = result+sk.pop();
}
return result;
}
public static void main(String args[])
{
String exp = "A*(B+C)*D";
System.out.println(converter(exp));
}
}