What is a Stack?

In this lesson, we will be introduced to the stack data structure, its uses, and its functionality.

Introduction #

We are all familiar with the famous Undo option, which is present in almost every application. Have you ever wondered how it works? The idea is that you store the previous states of your work (which are limited to a specific number), in the memory in such an order that the last one appears first. This can’t be done just by using arrays, which is why the Stack comes in handy.

You can think of the Stack as a container, in which we can add items and remove them. Only the top of this container is open, so the item we put in first will be taken out last, and the items we put in last will be taken out first. This is called the last in first out (LIFO) ordering.

A real-life example of a Stack can be a pile of books placed in a vertical order. So, to get the book that’s somewhere in the middle, you need to remove all the books placed on top of it. That is how the LIFO method works. The following figure illustrates a Stack:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.