Pages

Sunday, January 26, 2014

INFIX TO POSTFIX

GET THE INFIX EXPRESSION IN A BUFFER
INITIALIZE PRINT QUEUE
INITIALIZE OPERATOR STACK
WHILE BUFFER IS NOT EMPTY
    READ A TOKEN FROM THE BUFFER
    IF TOKEN IS OPERAND
       ENQUEUE THE TOKEN IN PRINT QUEUE
    ELSE IF TOKEN IS A OPERATOR
        IF OPERATOR STACK IS EMPTY
            PUSH THE TOKEN IN THE OPERATOR STACK
        ELSE
            IF THE TOS (OPERATOR STACK) IS HIGHER PRIORITY OPERATOR THAN TOKEN
                ENQUEUE ( POP FROM OPERATOR STACK) INTO PRINT QUEUE
                PUSH THE TOKEN IN THE OPERATOR STACK
            ELSE
                PUSH THE TOKEN IN THE OPERATOR STACK
            END IF
        END IF
    ELSE IF TOKEN IS "("
        PUSH THE TOKEN IN THE OPERATOR STACK
    ELSE IF TOKEN IS ")"
        IF OPERATOR STACK IS EMPTY
            INFIX EXPRESSION IS NOT VALID
        ELSE
            WHILE TOS (OPERATOR STACK) IS NOT "(" AND OPERATOR STACK NOT EMPTY
                ENQUEUE ( POP FROM OPERATOR STACK) INTO PRINT QUEUE
            END WHILE
            IF OPERATOR STACK EMPTY
                INFIX EXPRESSION IS NOT VALID
            ELSE
                POP FROM OPERATOR STACK /* POP "(" */
            END IF
        END IF
    END IF
END WHILE
WHILE OPERATOR STACK IS NOT EMPTY
    ENQUEUE ( POP FROM OPERATOR STACK) INTO PRINT QUEUE
END WHILE

No comments: