import java.util.LinkedList;
import java.util.Stack;
public class InfixtoPostfix {
static Stack inputStack;
static String output = "";
public static void main(String[] args) {
String input = "1+2*4/5-7+3/6";
System.out.println(infixToPostfix(input));
}
public static String infixToPostfix(String input) {
inputStack = new Stack();
for (int i = 0; i < input.length(); i++) {
char current = input.charAt(i);
if (current == '+' || current == '-') {
isOperator(current, 1);
} else if (current == '*' || current == '/') {
isOperator(current, 2);
} else {
output += current;
}
}
while(!inputStack.isEmpty()){
char top = (Character) inputStack.pop();
output += top;
}
return output;
}
public static void isOperator(char c, int prec) {
while (!inputStack.isEmpty()) {
char top = (Character) inputStack.pop();
int topPrec = 0;
if (top == '+' || top == '-') {
topPrec = 1;
} else {
topPrec = 2;
}
if (topPrec >= prec) {
output += top;
}else{
inputStack.push(top);
break;
}
}
inputStack.push(c);
}
}
No comments:
Post a Comment