DEV Community

Cover image for Stack Data Structure
Aya Bouchiha
Aya Bouchiha

Posted on • Updated on

Stack Data Structure

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."

stack data structure

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
Enter fullscreen mode Exit fullscreen mode

References and useful Ressources

thank you!
#day_2

Top comments (0)