Back

How Stacks Work

A stack is an ordered collection of items with a base (the bottom of the stack) and a top. To add a new item to a stack, it is ‘pushed’ on top of the other items. A stack is a Last In First Out (LIFO) data structure, meaning items on top of the stack are removed before ones at the bottom. To remove items, they must be ‘popped’ from the top of the stack. To access items deeper down in the stack, multiple pop operations must be completed sequentially.

To remember how stacks work, think of a tower of blocks. You can’t remove one from the bottom as the tower would fall – therefore, blocks are removed (via pop) from the top of the tower until the desired block is reached. To add a new block, it is placed at the top of the tower (via push).

Stacks usually have a pointer to the top item, which will be incremented when a new item is pushed on. Random access of stack elements is not possible.