awelgorithms

Understand LIFO

Updated

LIFO means last in, first out. The value you pushed most recently is the only one you can pop next. Older values sit underneath until the newer ones are gone.

What to focus on

Push order 4, then 1, then 9. Emptying the stack without interleaving pops 9, then 1, then 4. Interleaved pushes and pops can yield other legal orders (for example 1, 9, 4). A queue would expose 4 first.

Worked examples

three pushes

a = [], push 4, 1, 9
  1. top becomes 4, then 1, then 9

Result: full drain pops 9, 1, 4

push push pop

a = [], push 4, push 1, pop
  1. pop yields 1
  2. 4 is still underneath

Result: stack is [4], popped 1

not FIFO

a = [4, 1, 9], pop expecting 4 first
  1. 4 is buried
  2. the legal pop is 9

Result: illegal if you wanted 4

Try it

Write showLifo(a). a is the stack, written [bottom, ..., top]. Push 4, then 1, then 9 from []. Draining without more pushes pops 9, 1, 4. Then show push, push, pop leaves [4]. A queue would yield 4 first. From [] after push 4,1,9 a full drain pops 9,1,4. push,push,pop leaves [4].

Values are integers. Every pop in the drill happens on a non-empty stack.