awelgorithms

Create a stack

Updated

A stack is a pile of values with one open end. Creating one means starting with no items and agreeing that every later change happens only at the top.

What to focus on

We write a = [bottom, …, top]. The last slot is the top. Empty is []. After creation there is no legal pop or peek until you push.

Worked examples

empty

no values
  1. allocate an empty stack
  2. there is no top

Result: [] · size 0

one value

place 7 as the only item
  1. bottom and top are both 7

Result: [7] · top 7

three values

place 4, then 1, then 9
  1. 4 is bottom
  2. 9 is top

Result: [4, 1, 9] · top 9

Try it

Write create(values). values is a list of integers to push left to right. The last value becomes the top. Push each value in order. Print size and top. Empty has no top. On [] size is 0. On [7] size is 1 and top is 7. On [4, 1, 9] size is 3 and top is 9.

values is a list of integers. You may create an empty stack.