Stack Machine Simulator

Stack Simulation Algorithm

Stack Machine Simulator

Create a function that simulates a simple stack machine. The machine starts with an empty stack and processes a list of instructions sequentially. It supports the following operations:

  • PUSH X: Push the integer X onto the stack.
  • POP: Remove the top element from the stack.
  • ADD: Pop the top two elements, add them, and push the result.
  • SUB: Pop the top two elements, subtract the top element from the second top element, and push the result.
  • MUL: Pop the top two elements, multiply them, and push the result.
  • DIV: Pop the top two elements, perform integer division of the second top element by the top element, and push the result.

Important:

  • If an operation cannot be performed due to insufficient elements on the stack or if division by zero occurs, return the string Error.
  • At the end of processing all instructions, return the final stack as a list where the bottom element is at index 0.

Example:

simulateStack(["PUSH 5", "PUSH 3", "ADD"])  // returns [8]

This problem helps you practice stack usage in algorithm design. Interestingly, on April 11, many new ideas in computing and engineering have taken root, making this a great day to explore fundamental data structures such as stacks!