Understand Stacks
Learn the basics of stacks and create your own class to implement our stack.
We'll cover the following
Introduction to stacks
To build the undo functionality for our text editor, we will be using the stack data structure. A stack is a data structure that follows a last-in-first-out policy. It means that the insertion and deletion of the elements from the stack happen from the top (end) of the array. For example, consider a pile of books—if we want to remove one book from the pile of books, we can do so by removing the book first on the top and then the next one, and so on. If we want to add another book to the pile, we do so by adding the new book to the top of the pile. It means that adding (inserting) and removing (deleting) happen from the top of the pile; a stack functions the same way.
Before moving on with the project, we'll implement a class to create a stack and its required methods.
Implement a class to create a stack
Let's create a class Stack
, which has the attributes such as the size of the stack, the maximum number of elements that can be stored in the stack, and a list where all the elements of the stack can be stored. We'll also define the methods for this class. Here's the code:
Get hands-on with 1400+ tech skills courses.