forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfix.java
More file actions
73 lines (62 loc) · 2.15 KB
/
InfixToPostfix.java
File metadata and controls
73 lines (62 loc) · 2.15 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
package com.geeksforgeeks.stack;
import java.util.*;
public class InfixToPostfix {
static List<Character> operators = Arrays.asList('+', '*', '/', '-', '(', ')', '^');
static Map<Character, Integer> precedenceMap = new HashMap<>();
static {
precedenceMap.put('^', 3);
precedenceMap.put('*', 2);
precedenceMap.put('/', 2);
precedenceMap.put('+', 1);
precedenceMap.put('-', 1);
precedenceMap.put('(',0);
}
public static void main(String[] args) {
infixToPostfix("a+b*(c^d-e)^(f+g*h)-i");
}
public static void infixToPostfix(String str) {
char[] input = str.toCharArray();
Stack<Character> stack = new Stack<>();
char temp = 'c';
for (char c : input) {
if (!isOperator(c)) {
System.out.print(c);
} else {
if (c == '(') {
stack.push('(');
} else if (c == ')') {
while (!stack.isEmpty() && (temp = stack.peek()) != '(') {
System.out.print(stack.pop());
}
if(temp == '(') {
stack.pop();
} else {
if(!stack.isEmpty()) {
System.out.println("Invalid Expression");
}
}
} else {
while (!stack.isEmpty() && !inputHasGreaterPrecedence(stack.peek(), c)) {
System.out.print(stack.pop());
}
stack.push(c);
}
}
}
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
public static boolean inputHasGreaterPrecedence(Character stackTop, Character input) {
int inputPriority = precedenceMap.get(input);
int stackTopPriority = precedenceMap.get(stackTop);
if (stackTopPriority < inputPriority) {
return true;
} else {
return false;
}
}
public static boolean isOperator(Character c) {
return operators.contains(c);
}
}