Stack is an abstract data type that serves as a collection of elements. To keep the order as a real stack, LIFO (Last In First OIt) rule is followed. This abstract data type is implemented with three methods:
- PUSH - Insert elements at the top of the stack.
- POP - Remove elements at the top of the stack and return them.
- PEEK - Return the element at the top of the list without pop it.
| Algorithm | Average | Worst case |
|---|---|---|
| Memory Space | O(n) | O(n) |
| Search | -- | -- |
| Insert | O(1) | O(1) |
| Delete | O(1) | O(1) |
One great exemple of Stack is in a math expression compiler calculator. Queue is also used in this process, but stack presence is essential.
Import
from AbstractDataTypes import StackCreate a Stack Instance
max_size specific the how many elements Queue can have. Stack(max_size=0) or Stack() create a ilimited stack.
You can also initialize Stack with values, just passing an __ iter __ object.
s = Stack()
print(s)
# <|
s = Stack([0, 2, 4, 6, 8])
print(s)
# <8, 6, 4, 2, 0|PUSH method
s.push(10)
print(s)
# <10, 8, 6, 4, 2, 0|POP method
poped_item_1 = s.pop()
print(poped_item_1)
# 10
poped_item_2 = s.pop()
print(poped_item_2)
# 8
print(s)
# <6, 4, 2, 0|PEEK method
print(s.peek())
# 6
print(s)
# <6, 4, 2, 0|