Introduction
Wow, it has been so long since I wrote my last blog about Data Structures and Algorithms. If you want to read the previous publications on this series here are the links for your convenience:
Data Structures and Algorithms in Swift: Arrays
Data Structures and Algorithms in Swift: Linked Lists
Today I want to write about another very well known data structure called Stack. As the name suggests, the stack data structure arranges elements on top of each other, i.e. stacks them up. Some other examples of stacks include stacks of books, stack of paper, stack of cash, stack dinner plates. etc. The Stack data structure is similar in concept to a physical stack of objects like the ones mentioned above. This means that if you want to take an element from the top, it must be taken from the top. When you insert an element in the stack, it must be inserted on top of existing elements. So, you can say that a Stack is also a LIFO (Last-In First-Out) data structure.
Stacks are very useful and simple to implement. By design a Stack data structure enforces how you interact with the elements inside it. The two main operations in a stack are as follows:
- push — inserts an element to the top of the stack