data-structures-and-algorithms
Stack

Stack

What is stack?

Stack is a Last In First Out (LIFO) manner and it is built by dynamic array. That means the last element added will be the 1st element to come out first.

stack

OperationBig-O Time
PushO(1)
PopO(1)
Peek / TopO(1)
class Stack:
    def __init__(self) -> None:
        self.stack = []
 
    def __len__(self) -> int:
        return len(self.stack)
 
    def push(self, n) -> None:
        self.stack.append(n)
 
    def pop(self):
        if len(self) == 0:
            raise Exception("Stack is empty")
        return self.stack.pop()
 
    def peek(self):
        if len(self) == 0:
            raise Exception("Stack is empty")
        return self.stack[-1]