Want to try solving this problem? You can submit your code online if you log in or register.
Input File: rpnin.txt
Output File: rpnout.txt
Implement a stack and show it off by writing a programme which reads input from rpnin.txt. After each line of input, print out the contents of the stack, and execute the command given in the table below. If the stack is empty after a pop, print 'stack is empty!'.
+ | Pop the top two numbers n_{1} and n_{2} off the stack and push (n_{1} + n_{2}) on |
- | Pop the top two numbers n_{1} and n_{2} off the stack and push (n_{2} — n_{1}) on |
* | Pop the top two numbers n_{1} and n_{2} off the stack and push (n_{1} × n_{2}) on |
/ | Pop the top two numbers n_{1} and n_{2} off the stack and push (n_{2} / n_{1}) on |
swap | Exchange the top two numbers on the stack |
dup | Duplicate the top of the stack |
p | Pop the top number off the stack |
q | Terminate the program, do not print the stack for this line. |
otherwise | If the input is not a command from above, it is an integer to put on the stack. |
You may assume that your stack does not grow beyond 1000 levels deep.
Sample input:
1 2 + 4 * 2 / 10 swap - dup p 5 - p q
Sample output:
1 1 2 3 3 4 12 12 2 6 6 10 10 6 4 4 4 4 4 5 -1 stack is empty!
Privacy
statement
© Australian Mathematics Trust 2001-2023
Page generated: 3 June 2023, 3:25pm AEST