0% found this document useful (0 votes)
15 views2 pages

Infix Program

infix program

Uploaded by

sas28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views2 pages

Infix Program

infix program

Uploaded by

sas28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

Scanner;

import java.util.Stack;

public class InfixToPostfix {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter an infix expression:");

String infix = scanner.nextLine();

System.out.println("Postfix Expression: " + convertToPostfix(infix));

private static String convertToPostfix(String infix) {

StringBuilder postfix = new StringBuilder();

Stack<Character> stack = new Stack<>();

for (char c : infix.toCharArray()) {

if (Character.isLetterOrDigit(c)) {

postfix.append(c);

} else if (c == '(') {

stack.push(c);

} else if (c == ')') {

while (!stack.isEmpty() && stack.peek() != '(') {

postfix.append(stack.pop());

stack.pop();

} else {

while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) {

postfix.append(stack.pop());

stack.push(c);

}
}

while (!stack.isEmpty()) {

postfix.append(stack.pop());

return postfix.toString();

private static int precedence(char op) {

return switch (op) {

case '+', '-' -> 1;

case '*', '/' -> 2;

case '^' -> 3;

default -> -1;

};

You might also like