awelgorithms

Why a stack reverses order

Updated

Each push hides the previous top. Drain order is therefore the opposite of insertion order. That is LIFO. Any reverse-this-sequence is a candidate for a stack.

What to focus on

If you needed the same order out as in, you wanted a queue. If you needed reverse, a stack (or an explicit reverse pass) is the structure.

Worked examples

in vs out

a = [4, 1, 9]
  1. in 4,1,9
  2. out 9,1,4

Result: reversed

one is identity

a = [7]
  1. in 7 out 7

Result: same

queue contrast

a = [4, 1, 9] as a queue
  1. out would be 4,1,9

Result: not reversed

Try it

Write drainOrder(a). a is an array of integers to push left to right. Push then drain. Label in-order versus out-order. A queue would leave the same order. Push [4, 1, 9] and drain 9,1,4. A queue would yield 4,1,9. [7] is reverse-identity.

The sequence is non-empty. Values are integers.