Wikipedia: Infix to Postfix Conversion Extract

http://en.wikipedia.org/wiki/Shunting_yard_algorithm

This has been simplified to remove the processing of function calls / method invocations.  — tjr

The algorithm in detail

Read a token.
  • If the token is a number, then add it to the output queue.
  • Else if the token is an operator, o1, then:
1) 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 or equal to that of o2, or
o1 is right-associative and its precedence is less than that of o2,
pop o2 off the stack, onto the output queue;
2) push o1 onto the operator stack.
  • Else if the token is a left parenthesis, then push it onto the stack.
  • Else if the token is a right parenthesis, then pop operators off the stack, onto the output queue, until the token at the top of the stack is a left parenthesis, at which point it is popped off the stack but not added to the output queue. If the stack runs out without finding a left parenthesis, then there are mismatched parentheses.

Complex example

Input 3+4*2/(1-5)^2
Read "3"
 Add "3" to the output
  Output: 3

Read "+"
 Push "+" onto the stack
  Output: 3
  Stack: +

Read "4"
 Add "4" to the output
  Output: 3 4
  Stack: +

Read "*"
 Push "*" onto the stack
  Output: 3 4
  Stack: + *

Read "2"
 Add "2" to the output
  Output: 3 4 2
  Stack: + *

Read "/"
 Pop "*" off stack and add it to output, push "/" onto the stack
  Output: 3 4 2 *
  Stack: + /

Read "("
 Push "(" onto the stack
  Output: 3 4 2 *
  Stack: + / (

Read "1"
 Add "1" to output
  Output: 3 4 2 * 1
  Stack: + / (

Read "-"
 Push "-" onto the stack
  Output: 3 4 2 * 1
  Stack: + / ( -

Read "5"
 Add "5" to output
  Output: 3 4 2 * 1 5
  Stack: + / ( -

Read ")"
 Pop "-" off stack and add it to the output, pop (
  Output: 3 4 2 * 1 5 -
  Stack: + /

Read "^"
 Push "^" onto stack
  Output: 3 4 2 * 1 5 -
  Stack: + / ^

Read "2"
 Add "2" to output
  Output: 3 4 2 * 1 5 - 2
  Stack: + / ^

End of Expression
 Pop stack to output
  Output: 3 4 2 * 1 5 - 2 ^ / +