|
| 1 | +package Stack; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.Deque; |
| 5 | + |
| 6 | +public class Postfix2 { |
| 7 | + |
| 8 | + static int Prec(char ch) |
| 9 | + { |
| 10 | + switch (ch) { |
| 11 | + case '+': |
| 12 | + case '-': |
| 13 | + return 1; |
| 14 | + |
| 15 | + case '*': |
| 16 | + case '/': |
| 17 | + return 2; |
| 18 | + |
| 19 | + case '^': |
| 20 | + return 3; |
| 21 | + } |
| 22 | + return -1; |
| 23 | + } |
| 24 | + |
| 25 | + static String infixToPostfix(String exp) |
| 26 | + { |
| 27 | + // Initializing empty String for result |
| 28 | + String result = new String(""); |
| 29 | + |
| 30 | + // Initializing empty stack |
| 31 | + Deque<Character> stack |
| 32 | + = new ArrayDeque<Character>(); |
| 33 | + |
| 34 | + for (int i = 0; i < exp.length(); ++i) { |
| 35 | + char c = exp.charAt(i); |
| 36 | + |
| 37 | + // If the scanned character is an |
| 38 | + // operand, add it to output. |
| 39 | + if (Character.isLetterOrDigit(c)) |
| 40 | + result += c; |
| 41 | + |
| 42 | + // If the scanned character is an '(', |
| 43 | + // push it to the stack. |
| 44 | + else if (c == '(') |
| 45 | + stack.push(c); |
| 46 | + |
| 47 | + // If the scanned character is an ')', |
| 48 | + // pop and output from the stack |
| 49 | + // until an '(' is encountered. |
| 50 | + else if (c == ')') { |
| 51 | + while (!stack.isEmpty() |
| 52 | + && stack.peek() != '(') { |
| 53 | + result += stack.peek(); |
| 54 | + stack.pop(); |
| 55 | + } |
| 56 | + |
| 57 | + stack.pop(); |
| 58 | + } |
| 59 | + |
| 60 | + // An operator is encountered |
| 61 | + else |
| 62 | + { |
| 63 | + while (!stack.isEmpty() |
| 64 | + && Prec(c) <= Prec(stack.peek())) { |
| 65 | + |
| 66 | + result += stack.peek(); |
| 67 | + stack.pop(); |
| 68 | + } |
| 69 | + stack.push(c); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + // Pop all the operators from the stack |
| 74 | + while (!stack.isEmpty()) { |
| 75 | + if (stack.peek() == '(') |
| 76 | + return "Invalid Expression"; |
| 77 | + result += stack.peek(); |
| 78 | + stack.pop(); |
| 79 | + } |
| 80 | + |
| 81 | + return result; |
| 82 | + } |
| 83 | + public static void main(String[] args) { |
| 84 | + String exp = "a+b*(c^d-e)^(f+g*h)-i"; |
| 85 | + |
| 86 | + // Function call |
| 87 | + System.out.println(infixToPostfix(exp)); |
| 88 | + } |
| 89 | +} |
0 commit comments