Download example slides

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Reverse Polish Notation
Written by J.J. Shepherd
Reverse Polish Notation
• Most math expressions you have seen were
written in “in-fix” notation
• Example:
3+5
• However there is another notation called “postfix” or “Revere Polish Notation” where the
operator is at the end
• Example
35+
Big Idea
• Use a stack to solve reverse polish notation
• You push onto the stack when there’s a
number
• When there’s an operator (+, -, *, /) then
– Pop off two items from the stack
– Evaluate the two numbers with that operation
– Push the result back to the stack
• Once it has completed the expression there
should only be one item left on the stack
Reverse Polish Example
• Here the user has inputted the string 3 2 +
3 2 +
Head
Tail
Reverse Polish Example
• 3 is a number so push it on the stack
3 2 +
3
Head
Tail
Reverse Polish Example
• 2 is a number so push it on the stack
3 2 +
2
Head
3
Tail
Reverse Polish Example
• + is an operator so pop of two
3 2 +
2
Head
3
Tail
Reverse Polish Example
• + is an operator so pop of two
3 2 +
+2
POP
2
Head
3
Tail
Reverse Polish Example
• + is an operator so pop of two
3 2 +
3+2
3POP
Head
Tail
Reverse Polish Example
• Evaluate
3 2 +
5
Head
Tail
Reverse Polish Example
• Push the value back
3 2 +
5
5
Head
Tail
Reverse Polish Example
• DONE!
3 2 +
5
Head
Tail
Reverse Polish Example
• Here the user has inputted the string 8 2 – 3 *
8 2 – 3 *
Head
Tail
Reverse Polish Example
• 8 is a number so push it on the stack
8 2 – 3 *
8
Head
Tail
Reverse Polish Example
• 2 is a number so push it on the stack
8 2 – 3 *
2
Head
8
Tail
Reverse Polish Example
• - is an operator so pop of two
8 2 – 3 *
2
Head
8
Tail
Reverse Polish Example
• + is an operator so pop of two
8 2 – 3 *
-2
POP
2
Head
8
Tail
Reverse Polish Example
• + is an operator so pop of two
8 2 – 3 *
8-2
3POP
Head
Tail
Reverse Polish Example
• Evaluate
8 2 – 3 *
6
Head
Tail
Reverse Polish Example
• Push the value back
8 2 – 3 *
6
6
Head
Tail
Reverse Polish Example
• 3 is a number so push it onto the stack
8 2 – 3 *
3
Head
6
Tail
Reverse Polish Example
• * is an operator so pop of two
8 2 – 3 *
*3
POP
2
Head
6
Tail
Reverse Polish Example
• * is an operator so pop of two
8 2 – 3 *
6*3
POP
6
Head
Tail
Reverse Polish Example
• Evaluate
8 2 – 3 *
18
Head
Tail
Reverse Polish Example
• Push the value back
8 2 – 3 *
18
18
Head
Tail
Reverse Polish Example
• DONE!
8 2 – 3 *
18
Head
Tail
Related documents