Stack data structure

Posted by : at

Explaining the basics of the stack data structure

In this blogpost the stack data structure will be explained in more detail. There will be an accompanying video to help explain the stack with animations.

Because different languages use different operations on the stack data structure, this blogpost will use the most common operation or function names. Please lookup the actual method or function names for the language you’re using.

What is a stack?

Well to put simply, a stack a data structure in which you can store multiple elements. Each element is added at the end of the stack and only the last added element of the stack can be referenced. This follows the LIFO (last in, first out) principle.

How does it work?

The stack works by providing at least three operations on the data structure, the push, pop and peek (although this might also be called top in some languages).


When trying to retrieve an element from the stack, most implementations use the peek operation to get the top most element in the stack. The peek operation will always return the latest added element in the stack, or null/nullptr when no elements are present in the stack.


The push operations requires a variable as argument and will place that variable to the top of the stack. When an element gets pushed onto the stack, the peek operation will move up the stack to the new top most element. Thus returning the variable that’s just been added to the stack.


To remove items from the stack the pop operation is used. This operation doesn’t accept any arguments and will always remove the top most element from the stack. When the element is removed, the peek operation will automatically point to the element that was added before the removed element was added.