Untitled
unknown
plain_text
2 years ago
3.4 kB
4
Indexable
import java.util.*; public class InfixToPostfix { // This method returns the precedence of the operator public static int getPrecedence(char ch) { switch(ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } // This method converts an infix expression to postfix expression public static String infixToPostfix(String infix) { Stack<Character> stack = new Stack<>(); StringBuilder postfix = new StringBuilder(); for(int i = 0; i < infix.length(); i++) { char ch = infix.charAt(i); if(Character.isLetterOrDigit(ch)) { postfix.append(ch); } else if(ch == '(') { stack.push(ch); } else if(ch == ')') { while(!stack.isEmpty() && stack.peek() != '(') { postfix.append(stack.pop()); } stack.pop(); } else { while(!stack.isEmpty() && getPrecedence(ch) <= getPrecedence(stack.peek())) { postfix.append(stack.pop()); } stack.push(ch); } } while(!stack.isEmpty()) { if(stack.peek() == '(') { return "Invalid Expression"; } postfix.append(stack.pop()); } return postfix.toString(); } // This method evaluates a postfix expression public static int evaluatePostfix(String postfix) { Stack<Integer> stack = new Stack<>(); for(int i = 0; i < postfix.length(); i++) { char ch = postfix.charAt(i); if(Character.isDigit(ch)) { stack.push(ch - '0'); } else { int operand2 = stack.pop(); int operand1 = stack.pop(); int result = 0; switch(ch) { case '+': result = operand1 + operand2; break; case '-': result = operand1 - operand2; break; case '*': result = operand1 * operand2; break; case '/': result = operand1 / operand2; break; case '^': result = (int) Math.pow(operand1, operand2); break; } stack.push(result); } } return stack.pop(); } // Main method to test the program public static void main(String[] args) { String infix = "2+3*4-5"; String postfix = infixToPostfix(infix); System.out.println("Postfix notation: " + postfix); int result = evaluatePostfix(postfix); System.out.println("Result: " + result); } }
Editor is loading...