postfix-notationinfix-notationprefix-notation

How can I check whether the given expression is an infix expression, postfix expression or prefix expression?


I need algorithms that will check whether given expression is infix, postfix or prefix expression. I have tried a method by checking first or last 2 terms of the string e.g.

+AB if there is an operator in the very first index of string then its a prefix

AB+ if there is an operator in the very last index of string then its a postfix

else it is an infix.

But it doesn't feel appropriate so kindly suggest me a better algorithim.


Solution

    1. If it starts with a valid infix operator it's infix, unless you're going to allow unary operators.
    2. If it ends with a valid postfix operator it's postfix.
    3. Otherwise it is either infix or invalid.

    Note that (3) includes the case you mentioned in comments of an expression in parentheses. There are no parentheses in prefix or postfix. That's why they exist. (3) also includes the degenerate case of a single term, e.g. 1, but in that case it doesn't matter how you parse it.

    You can only detect an invalid expression by parsing it fully.

    If you're going to allow unary operators in infix notation I can only suggest that you try all three parses and stop when you get a success. Very possibly this is the strategy you should follow anyway.