Convert Infix to Prefix: A Step-by-Step Guide with Program Implementation Using Java

preview_player
Показать описание
This is a Java program that converts an infix expression to a prefix expression. The program uses a stack data structure to convert the expression.

The program begins by defining two helper methods:

isOp(char c) determines whether a character is an operator. It returns true if the character is one of '+', '-', '/', '*', or '^'.

getPrecedence(char op) returns the precedence of an operator. It returns 1 for '+' and '-', 2 for '*' and '/', and 3 for '^'. If the character passed to the method is not an operator, it returns -1.

The infixtoprefix(String infix) method takes an infix expression as input and returns the corresponding prefix expression. The method first reverses the infix expression and stores the reversed string in a variable named reversed. It then initializes a stack called operatorstack, which will be used to store operators. The method also initializes a StringBuilder object called prefix, which will be used to store the prefix expression.

The method then iterates over the reversed string, character by character. If the character is a space, it is skipped. If the character is not an operator, it is appended to the prefix string. If the character is an operator, the method pops operators from the operator stack and appends them to the prefix string until the top operator on the stack has a lower precedence than the current operator. The current operator is then pushed onto the operator stack.

After the loop is finished, the remaining operators in the operator stack are popped and appended to the prefix string. The prefix string is then reversed and returned.

The main method of the program calls infixtoprefix with the input string "a * b - c" and prints both the input and output expressions to the console.
Рекомендации по теме
Комментарии
Автор

Can you add a pop mechanism for ( and ) and a scanner for input

DeniseMarasigan-mr
Автор

import java.util.Stack;
public class InfixtoPrefix{

static boolean isOp(char c){
return (c == '+' || c == '-' || c == '/' || c == '*' || c == '^');
}

static int getPrecedence(char op){
switch(op){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return -1;
}
}
static String infixtoprefix(String infix){
String reversed = new
Stack<Character> operatorstack = new Stack<Character>();
StringBuilder prefix = new StringBuilder();
for(int i = 0; i < reversed.length(); i++){
char c = reversed.charAt(i);
if( c == ' '){
continue;
}
if(!isOp(c)){
prefix.append(c);
}
else{
&& > getPrecedence(c)){

}
operatorstack.push(c);
}
}


}
String prefixs = prefix.reverse().toString();
return prefixs;
}
public static void main(String[] args) {
String infix = "a * b - c";
String prefix = infixtoprefix(infix);
System.out.println("infix " + infix);
System.out.println("prefix " + prefix);
}



}

acejaspers
visit shbcf.ru