Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- public class Demo{
- public static void main(String[] args){
- String infixExp = "a + b * c + ( d * e + f ) * g";
- System.out.println(infixToPostFix(infixExp));
- }
- public static String infixToPostFix(String infixExp) {
- // provide implementation here
- Stack<String> operators = new Stack<String>();
- String s1 = "";
- String[] split = infixExp.trim().split("\s+");
- for(int i = 0; i < split.length; i++){
- if(split[i].matches("[^()*/%+-]")){
- s1 = s1 + split[i] + " ";
- }else{
- switch(split[i]){
- case "(":
- operators.push(split[i]);
- break;
- case ")":
- while(operators.peek() != "("){ s1 = s1 + operators.pop() + " "; }
- operators.pop();
- break;
- case "*":
- case "/":
- case "%":
- operators.push(split[i]);
- break;
- case "+":
- case "-":
- if(!operators.isEmpty()){
- while(operators.peek() == "*" || operators.peek() == "/" || operators.peek() == "%" ){
- s1 = s1 + operators.pop() + " ";
- }
- }
- operators.push(split[i]);
- break;
- }
- }
- }
- return s1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement