awelgorithms

Read the stack from bottom to top

Updated

Bottom-to-top is the array writing [bottom, …, top]. Top-to-bottom is the pop order. Say which direction you are printing or you will reverse the stack on paper.

What to focus on

To print bottom-to-top without destroying the stack, walk the backing array 0..size-1, or pop into a helper and push back. Popping as you print is top-to-bottom.

Worked examples

bottom to top

a = [4, 1, 9]
  1. 4 then 1 then 9

Result: 4, 1, 9

top to bottom

a = [4, 1, 9]
  1. 9 then 1 then 4

Result: 9, 1, 4

one item

a = [7]
  1. same both directions

Result: 7

Try it

Write printBoth(a). a is the stack, written [bottom, ..., top]. Print bottom-to-top and top-to-bottom. Label them. A pop-loop prints top-first, not bottom-first. [4, 1, 9] bottom-to-top is 4, 1, 9. Top-to-bottom is 9, 1, 4. [7] is 7 either way.

The stack is non-empty. Values are integers.