Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathInfixtoPostfix.java
More file actions
Latest commit
81 lines (61 loc) · 1.32 KB
/
Copy pathInfixtoPostfix.java
File metadata and controls
81 lines (61 loc) · 1.32 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
importjava.util.Stack;
classTest
{
staticintPrec(charch)
{
switch (ch)
{
case'+':
case'-':
return1;
case'*':
case'/':
return2;
case'^':
return3;
}
return -1;
}
staticStringinfixToPostfix(Stringexp)
{
Stringresult = newString("");
Stack<Character> stack = newStack<>();
for (inti = 0; i<exp.length(); ++i)
{
charc = exp.charAt(i);
if (Character.isLetterOrDigit(c))
result += c;
elseif (c == '(')
stack.push(c);
elseif (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
result += stack.pop();
if (!stack.isEmpty() && stack.peek() != '(')
return"Invalid Expression"; // invalid expression
else
stack.pop();
}
else// an operator is encountered
{
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){
if(stack.peek() == '(')
return"Invalid Expression";
result += stack.pop();
}
stack.push(c);
}
}
while (!stack.isEmpty()){
if(stack.peek() == '(')
return"Invalid Expression";
result += stack.pop();
}
returnresult;
}
publicstaticvoidmain(String[] args)
{
Stringexp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(infixToPostfix(exp));
}
}