Here is explanation of Stack Data Structure using some diagrams and Video links and code explanations also
Author has write codes in Swift and in Xcode Catalina macOS . And explained in some lines using diagrams also with some screenshots and a little explain recommended video .
The stack data structure is identical, in concept, to a physical stack of objects. When you add an item to a stack, you place it on top of the stack. When you remove an item from a stack, you always remove the top-most item.
Stack operations
There are only two essential operations for a stack:
- push: Adding an element to the top of the stack.
- pop: Removing the top element of the stack.
This means that you can only add or remove elements from one side of the data structure. In computer science, a stack is known as a LIFO (last-in first-out) data structure. Elements that are pushed in last are the first ones to be popped out.
Now let’s understand the Code Part
As we all know the application of Stack , here we are going to implement the program . So starting by creating a struct of type T . We have written some protocols , then creating a variable as values and making them an array of type T . What is T ? using this cause we don’t know which kind of data type could be , so we are using type T . Then we are creating a mutating function for popping the element and returning the values.popLast() as type T . And same we are creating a peek function and push also . Then we are creating a variable as stack and passing stack in it as type Int . In further lines we are performing their methods by passing values .