# problems on postfix conversion

Show 80 post(s) from this thread on one page
Page 2 of 2 First 12
• 04-21-2008
blacksnake
here is the algorithm and a code below in converting infix notation

1) if you encounter "(" push on it on stack
Code:

`          if(x[i]=='('){stack.push(x[i]);}`
2) if you encounter operators (+,-,*,/) then compare the operators with the top of the stack.As long as the top of the stack has operators with higher or equal priority to the scanned operators you have to keep popping the stack and store it in result

* * If the token is an operator, o1, then:
Code:

`          else if((x[i]=='+')||(x[i]=='-')||(x[i]=='*')||(x[i]=='/'))`
* while there is an operator, o2, at the top of the stack, and either

o1 is associative or left-associative and its precedence is less than (lower precedence) or equal to that of o2, or
o1 is right-associative and its precedence is less than (lower precedence) that of o2, (i got confised with the algorithm)

pop o2 off the stack, onto the output queue;
Code:

`                  q=q+stack.pop(); //where q=is a string and stack.pop()=is an o2;`
* push o1 onto the stack.
Code:

`                  stack.push(x[i]); //where x[i] = o1`
Lastly you have to push the scanned operator on the stack
Code:

`                  stack.push(x[i]); //where x[i] = o1`
3)If you encounter any digits or alphabets then store in in result
Code:

`                    else if(isdigit(x[i])){q=q+x[i];}`
4)if you encounter ")" keep popping the stack unless you encounter "(" on the stack and store it in result
Code:

`          else if(x[i]==')'){q=q+stack.pop();}`
Lastly decrement top by 1 as "(" is of no importance to us
Code:

`          top=top-1;`
as i see, that I confused on the scanning of precedence of operators, can you show me clear understanding about the precedence of the operators?
• 04-21-2008
tabstop
The precedence of the operators:
( and ) aren't operators, so don't count
* and / are equally high
+ and - are equally low

The algorithm says to pop if the operator read in is "less than or equal to" the one on the stack. So + and - mean you have to pop every operator you see; * and / mean you have to pop other * and /.
Show 80 post(s) from this thread on one page
Page 2 of 2 First 12