Hello, in this article we're going to talk about stack;
Definition of Stack
"A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop."
Space and Time complexity
the space complexity of a stack is O(n)
push | pop | peek |
---|---|---|
O(1) | O(1) | O(1) |
implementation of a stack using list in python
class Stack :
def __init__(self):
self.items = []
self.top = 0
def push(self,data: any) -> any :
self.items.append(data)
self.top+=1
return data
def pop(self) -> any:
if self.top > 0 :
self.top -=1
return self.items.pop()
def peek(self) -> any:
if self.top > 0:
return self.items[-1]
def __len__(self) -> int:
return self.top
def clear(self) -> list:
self.items = []
self.top = 0
return self.items
def isEmpty(self) -> bool:
return self.items == []
def printAll(self) -> list:
return self.items
References and useful Ressources
- https://www.quora.com/What-are-the-advantages-and-disadvantages-of-stack-in-collection
- https://www.geeksforgeeks.org/stack-in-python/
- https://betterprogramming.pub/implementing-a-stack-in-javascript-73d1aa0483c1
thank you!
#day_2
Top comments (0)