Stack
So, now we're going to talk about stack, a linear data structure and also we will see its implementation. In another post which will be linked below later will discuss its uses.So what is a stack?
Visualise a pile of coins or a stack of trays put one over the other. The item that has been put at the last has to be removed first as it is over all the other items. Hence, it is a data structure that works on LIFO(Last in First out) principle. Which simply means that the element that has been added the last will be removed first.
It is a very useful data structure and has several applications like expression evaluation and HTML validator or a bracket matching verifier.
In this data structure we only have operations that take their effect only at one end of the list. Both, the front or the end of a list can be used to implement it but using the tail(back-end) of the list is more efficient.
The main operation or methods on a stack are -
- Push : Adds element at the top of the stack
- Pop : Removes the element at the top of the stack and returns it
- Peek : Returns the element at the top but doesn't remove it
- isEmpty : Returns True if the stack is empty else returns False.
- Size : Returns the size of the stack.
Here is the implementation of the stack class
To use this in other programs just make sure that this python file with just the implementation of the class is stored in the same folder as the program you're working on and then just add an import statement on the top of the new program with the name of the file you saved the implementation of stack with and now you will have access to the Stack class.
Comments
Post a Comment