Back

Real World Examples

Stacks are extremely useful for undo buttons in programs. When an action is completed, for example adding a new image to a Word document, it is pushed onto the stack. When undo is pressed, the item at the top is popped from the stack, meaning the image is removed from the document. Because stacks are LIFO data structures, items are undone in the exact opposite order they were completed, so when undoing multiple actions each one will complete before moving to the next one.

Stacks can also be used to evaluate postfix expressions. These are expressions that consist of two operands followed by a single operator,for example the result of the input ‘2 3 +’ is 5. The following steps are executed on the input:

  1. Read the next item from the input.
  2. If it is an operand (such as 10):
    ->Push the operand to the stack.
  3. If it is an operator (such as +):
    ->Pop the last two operands from the stack e.g. 5 and 2
    -> Perform the operation on them e.g. 5 + 2 = 7.
    -> Push the result to the stack.
  4. Repeat the above steps.