Handling parenthesis while converting infix expressions to postfix expressions

后端 未结 2 1964
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 13:44

I\'m working on a project in Java that requires me to convert an infix expression to a postfix expression. I am currently able to convert infix expressions to postfix with t

相关标签:
2条回答
  • 2020-11-22 14:10

    You need to push the left parenthesis onto the stack, and process the stack like so when you encounter a right parenthesis:

    // opening (
    if (in_fix.peek().type == 4) {   
        post_fix.push(in_fix.pop());
    }
    //closing )
    if(in_fix.peek().type == 5){
        while(!(post_fix.isEmpty() || post_fix.peek().type == 4)){
             postfixstr.append(post_fix.pop());
        }
        if (post_fix.isEmpty())
            ; // ERROR - unmatched )
        else
            post_fix.pop(); // pop the (
        in_fix.pop(); // pop the )
    } 
    
    0 讨论(0)
  • 2020-11-22 14:20

    Try this way:

        //opening Parenthesis 
            if (in_fix.peek().type == 4) {   
                        post_fix.push(in_fix.pop());
            }
            //closing Parenthesis 
            if(in_fix.peek().type == 5){
                 //Till opening parenthesis encountered in stack, append operators to postfix. and pop parenthesis and do not append to post_fix.
                 while(post_fix.peek().type!=4){
                     postfixstr.append(post_fix.pop());
                 }
                //finally pop left parenthesis from post_fix stack.
                post_fix.pop();
            } 
    
    0 讨论(0)
提交回复
热议问题